亲爱的我有一个小的html5 canvas项目,该示例从codepen获取示例,以使用html5 canvas拖放图像。示例工作正常,但是一旦放置新图像,我就会遇到问题,然后所有图像区域都重叠。下面是javascript代码
<script>
var imgW;
function drawImg() {
var x = document.getElementById('myCanvas');
var canvax = x.getContext('2d');
var imgElement = document.getElementById('imgCanvas');
var imgObj = new Image();
imgObj.src = imgElement.src;
var imgW = imgObj.width;
var imgH = imgObj.height;
var imgX = canvax.canvas.width * .5 - imgW * .5;
var imgY = canvax.canvas.height * .5 - imgH * .5;
imgObj.onload = function () {
canvax.clearRect(imgX, imgY, imgW, imgH);
canvax.drawImage(imgObj, imgX, imgY, imgW, imgH);
};
}
$(document).ready(function () {
$('.listImg li').draggable({ containment: 'document', opacity: 0.60, revert: false, helper: 'clone',
start: function () {
$('.infoDrag').text('Start Drag');
},
drag: function () {
$('.infoDrag').text('on Dragging');
},
stop: function () {
$('.infoDrag').text('Stop Dragging');
} });
$('#myCanvas').droppable({ hoverClass: 'dashborder', tolerance: 'pointer',
drop: function (ev, ui) {
var droppedItem = $(ui.draggable).clone();
var canvasImg = $(this).find('img');
var newSrc = droppedItem.find('img').attr('src');
canvasImg.attr("src", newSrc);
drawImg();
} });
$('#myCanvas').dblclick(function () {
$('#myCanvas').draggable();
});
});
</script>
我需要在放置新图像之前清除图像。我可能需要使用clearRect方法。但由于尝试了几次,但没有用。任何建议或指导将不胜感激,谢谢。
答案 0 :(得分:1)
您将向 clearRect()馈入的图像而不是使用(新加载的)图像的大小和位置作为边界矩形。
只需更改
canvax.clearRect(imgX, imgY, imgW, imgH);
到
canvax.clearRect(0, 0, x.width, x.height);