【发布时间】:2017-08-21 09:59:11
【问题描述】:
我目前正在尝试使用画布创建一个单页浏览器,您可以在其中随意单击以添加/放置图像。我已经得到了我想要工作的大部分内容,但是对于 jquery 和 canvas 来说非常陌生,我仍然不知道如何为我的图像设置最大尺寸。据我了解,当您没有在 css 中手动设置画布大小时,很难使画布上的图像完美工作,但我有一个调整大小的画布,所以我不太确定我是如何做到的解决这个问题。
我希望我放置的图像的最大高度/最大宽度为视口的 80%。我尝试在 css 中设置最大尺寸,但它没有做任何事情。
这是jsfiddle
$(document).ready(function () {
var images = [];
$("#siteload").fadeIn(1500);
$('.put').each(function() {
images.push($(this).attr('src'));
});
(function() {
var
htmlCanvas = document.getElementById('c'),
context = htmlCanvas.getContext('2d');
initialize();
img = new Image();
count = 0;
htmlCanvas.onclick= function(evt) {
img.src = images[count];
var x = evt.offsetX - img.width/2,
y = evt.offsetY - img.height/2;
context.drawImage(img, x, y);
count++;
if (count == images.length) {
count = 0;
}
}
function initialize() {
window.addEventListener('resize', resizeCanvas, false);
resizeCanvas();
}
function resizeCanvas() {
htmlCanvas.width = window.innerWidth;
htmlCanvas.height = window.innerHeight;
}
})();
});
$(".hvr_cnt").mouseenter(function () {
title = $("<div class='hvr_ttl'>" + $(this).children()[0].title + "</div>");
$(this).children()[0].title = "";
$(this).append(title);
});
$(document).mousemove(function(e){
$('.hvr_ttl').css({
top: e.pageY - $(".hvr_ttl").height()/2,
left: e.pageX - $(".hvr_ttl").width()/2
});
});
$(".hvr_cnt").mouseleave(function (e) {
$(this).children()[0].title = $($(this).children()[1]).html();
$(this).children()[1].remove();
});
body {
margin: 0;
padding: 0;
background: rgb(240, 240, 240);
width: 100%;
height: 100%;
border: 0;
color: rgb(40, 40, 40);
overflow: hidden;
display: block;
}
.slides {
display: none
}
#c {
display: block;
position: absolute;
left: 0px;
top: 0px;
}
.hvr_ttl {
display: block;
position: absolute;
pointer-events: none;
cursor: none;
}
.hvr_cnt {
cursor: none;
padding: none;
margin: none;
}
<body ontouchstart="">
<div class="hvr_cnt">
<canvas id="c" title="click"></canvas>
</div>
<ul class="slides">
<li><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/85/Smiley.svg/2000px-Smiley.svg.png" class="put" /></li>
<li><img src="https://emojipedia-us.s3.amazonaws.com/thumbs/160/google/56/thumbs-up-sign_1f44d.png" class="put" /></li>
</ul>
</body>
任何帮助将不胜感激:)
【问题讨论】:
-
你想把图片的高度和宽度设置为画布高度和宽度的80%吗?
-
是的。我将向列表中添加一些不同的图像,具有不同的比例,所以我需要它们是最大宽度/最大高度以保持比例
标签: javascript jquery html css canvas