问题
Alright guys, I have been trying to get this for hours now, I cannot find anything.
Can someone type up a quick script, or point me in the direction of a tutorial for this..
I want to have an image (imgObj) come up on the canvas when the user clicks on the canvas. I want the image to come up at the coordinates that the mouse is at when the user clicks.
Any ideas?
Thanks a lot!
回答1:
You could start here: http://www.html5canvastutorials.com/
This is a tutorial on the HTML5 Canvas.
KineticJS is a library that makes this really easy: http://www.kineticjs.com/
essentially with KineticJS you can use the following methods to achieve your goal:
container.on("mousedown", function(){
image.show();
});
container.on("dragmove", function(){
var mousePos = container.getMousePosition();
var x = mousePos.x;
var y = mousePos.y;
image.move( x, y )
});
container.on("dragend"), function(){
image.hide();
});
回答2:
Really sorry for the late response. I know this question is older than God, but there isn't an accepted answer yet, so I thought I'd put in my two cents for the people who don't want to use external libraries.
I wrote a minimalistic script for you that will do what you want - just change fillRect() to drawImage() accordingly.
var cn = document.getElementById("main");
var c = cn.getContext("2d");
var mouse = {x:0, y:0};
window.addEventListener('mousedown', mHandler);
function mHandler(event) {
mouse.x = event.clientX;
mouse.y = event.clientY;
};
function main() {
c.clearRect(0, 0, cn.width, cn.height);
c.fillStyle = "red";
c.fillRect(mouse.x, mouse.y, 50, 50);
}
setInterval(main, 1000 / 60);
Here is a JSFiddle of a working example: http://jsfiddle.net/96s20d7m/
I'm setting the x and y values to where you clicked on the canvas, and then drawing something there with fillRect().
Note that this won't always work as expected, because pageX and pageY change based on borders, padding, margins, etc. You can see this in the Fiddle. To make this work, simply change pageX/Y to offsetX/Y, or use a polyfill.
Something like this in the mHandler function will work a bit better:
if(event.offsetX && event.offsetY) {
mouse.x = event.offsetX;
mouse.y = event.offsetY;
}
else {
mouse.x = event.layerX;
mouse.y = event.layerY;
}
Or if you want to shorten it up:
mouse.x = event.offsetX ? event.offsetX : event.layerX;
mouse.y = event.offsetY ? event.offsetY : event.layerY;
And then you can just call
context.drawImage(imgObj, mouse.x, mouse.y, imgObj.width, imgObj.height);
If you want the picture in the center of the mouse click, just call
context.drawImage(
imgObj,
mouse.x - imgObj.width / 2,
mouse.y - imgObj.height / 2,
imgObj.width, imgObj.height
);
Like this: http://jsfiddle.net/96s20d7m/4/
Again, substitute the rectangle for your image.
I hope this helped anyone reading this years later!
来源:https://stackoverflow.com/questions/9370503/html5-canvas-add-image-on-mouse-click-at-mouse-coordinates