Dear I have small html5 canvas project that getting example from codepen to drag&drop image using html5 canvas. Example work fine, but I have problem once new image placed, then all of them are overlap in image area. Below is javascript code
<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>
My need is to clear image before place new image. I may need to use clearRect method. But since tried several but not work. Any advise or guidance would be greatly appreciated, Thanks.
Instead of using the size and position of a (newly) loaded image as the bounding rectangle you feed to clearRect() use the size of the canvas itself.
Simply change
canvax.clearRect(imgX, imgY, imgW, imgH);
to
canvax.clearRect(0, 0, x.width, x.height);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.