【发布时间】:2015-01-23 12:45:24
【问题描述】:
我想要一个带有背景图像的画布,并在顶部绘制矩形。这些矩形在我的应用程序中称为热点。他们被画在画布上,然后很快消失。我怎样才能让他们留下来?
appendSection() 首先用 appendPicture() 附加一个图片,它只是将一个画布附加到一个 div,然后在该函数运行之后,创建画布和上下文,然后对于每个热点,在这种情况下有 3 个,它会画一个矩形,它会画一个矩形,然后它们就会消失。
function appendSection(theSection, list) {
list.append('<label class="heading">' + theSection.description + '</label><br/><hr><br/>');
if (theSection.picture) {
appendPicture(list, theSection);
var canvas = document.getElementById('assessmentImage');
var ctx=canvas.getContext("2d");
var img=new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0,canvas.width,canvas.height);
}
img.src = "data:image/jpeg;base64,"+ theSection.picture;
if(theSection.allHotSpots.length > 0) {
for( var x = 0; x < theSection.allHotSpots.length; x++) {
appendHotSpot(list, theSection.allHotSpots[x], theSection.thePicture, ctx);
}
}
}
appendSectionQuestions(theSection, list);
if (theSection.allSubSections) {
for (var x = 0; x < theSection.allSubSections.length; x++) {
var theSectionA = theSection.allSubSections[x];
appendSection(theSectionA, list);
}
}
}
function appendHotSpot(list, HotSpot, picture, ctx) {
var imageWidth = document.getElementById('assessmentImage' + platform).clientWidth;
var imageHeight = document.getElementById('assessmentImage' + platform).clientHeight;
var xScale = imageWidth / picture.xSize;
var yScale = imageHeight / picture.ySize;
HotSpot.topLeft = [Math.round(HotSpot.topLeft[0] * xScale), Math.round(HotSpot.topLeft[1] * yScale)];
HotSpot.bottomRight = [Math.round(HotSpot.bottomRight[0] * xScale), Math.round(HotSpot.bottomRight[1] * yScale)];
var rect = {x1: HotSpot.topLeft[0], y1: HotSpot.topLeft[1], x2: HotSpot.bottomRight[0], y2: HotSpot.bottomRight[1]};
ctx.fillStyle = "#FF0000";
ctx.fillRect(rect.x1, rect.y1, rect.x2, rect.y2);
//addRect("blue", rect);
}
function appendPicture(list, theSection) {
list.append('<div id="wrapper' + platform + '" style="width:100%; text-align:center">\
<canvas class="assessmentImageSmall" style="width:100%;" id="assessmentImage' + platform + '" align="middle" ></canvas>\
<!--<p style="color:#666;" id="imageInstruction">Tap image to enlarge.</p>-->\
</div>');
$("#wrapper").kendoTouch({
tap: function (e) {
switchImage();
}
});
}
【问题讨论】:
-
画布是否每隔几毫秒就不断更新?如果是这样,您需要在画布更新时重新绘制矩形。
-
如果背景除了显示静态图像之外没有其他用途,您可以在 CSS 中指定画布的背景。
-
感谢@RickyAYoder,您的解决方案也不错。
标签: javascript canvas draw