javascript 使用鼠标拖动在 HTML 画布内移动图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21945241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Move image inside HTML canvas with mouse dragging
提问by BeoWulf
I have one image that I need to resize, move, and rotate inside a Canvas, and than another image that I use as a mask to clip the other image using globalCompositeOperation = "source-in";
我有一个图像需要在 Canvas 内调整大小、移动和旋转,而不是我用作遮罩的另一个图像使用 globalCompositeOperation = "source-in";
Here is a fiddle.
这是一个小提琴。
I was thinking about to add buttons to move the image but why not the mouse? However, I can't find a way how to integrate a dragging function in this code. What do I need to change or hadd here?
我正在考虑添加按钮来移动图像,但为什么不添加鼠标?但是,我找不到如何在此代码中集成拖动功能的方法。我需要改变什么或在这里有什么?
回答by acarlon
Original - move outer image
原始 - 移动外部图像
See this jsfiddle
看到这个jsfiddle
Code:
代码:
$(window).mousemove(function(event) {
$("#stcanvas").css({"left" : event.pageX, "top" : event.pageY});
});
css:
css:
#stcanvas
{
position:absolute;
}
You would obviously add a button to enable movement. Alternatively, you may want to use jquery UI for in-built drag and drop.
您显然会添加一个按钮来启用移动。或者,您可能希望使用 jquery UI 进行内置拖放。
Update - move clip
更新 - 移动剪辑
See this jsfiddle.
看到这个 jsfiddle。
If what you mean is that you would like to move the clip rather than the image, then do something like this:
如果您的意思是要移动剪辑而不是图像,请执行以下操作:
$(window).mousemove(function(event) {
var cWidth = $("#stcanvas").width();
moveXAmount = (event.pageX / $(window).width())*cWidth;
moveXAmount = moveXAmount - (cWidth/2);
var cHeight = $("#stcanvas").height();
moveYAmount = (event.pageY / $(window).height())*cHeight;
moveYAmount = moveYAmount - (cHeight/2);
buildcanvas();
});
and in make_pic
do this:
并make_pic
这样做:
ctx.drawImage(mask_image, moveXAmount, moveYAmount);
Update 2 - move clip and inner image
更新 2 - 移动剪辑和内部图像
see this fiddle
看到这个小提琴
If you want to move the image and the clip, then , basically you just add the moveXAmount and moveYAmount to drawImage. Hopefully I have exhausted all possibilities now ;)
如果你想移动图像和剪辑,那么,基本上你只需将 moveXAmount 和 moveYAmount 添加到 drawImage。希望我现在已经用尽了所有的可能性;)
ctx.drawImage(pic_image, -400 / 2+moveXAmount, -550 / 2+moveYAmount, im_width, im_height);
Update 3 move image and not mask as per comment
根据评论更新 3 移动图像而不是遮罩
See this fiddle
看到这个小提琴
The main change is:
主要变化是:
$("#stcanvas").mousedown(function(){
isDragging = true;
});
$(window).mouseup(function(){
isDragging = false;
});