I have create a drawing canvas. In javascript.
But when i move my mouse fast i haven't a full line but a line with points.
I have used an arc for this i dont know of there is a better option for painting a line
How can i fix this ??
already thanks
<script type="application/javascript" src="jquery.js"></script>
<script>
var canvas;
var ctx;
var StartDraw = false;
var dikte = 7;
$(document).ready(DoInit());
function DoInit()
{
canvas = document.getElementById("canvas");
ctx = canvas.getContext('2d');
$(".kleur").on('click',doKleur);
$("canvas").on('mouseup',DoUp);
$("canvas").on('mousedown',DoDown);
$("canvas").on('mousemove',DoMove)
$("#dikte").on('change',doDikte);
$(".clear").on('click',clear);
}
function doDikte(){
dikte = this.value;
}
function clear(){
ctx.clearRect(0,0,canvas.width,canvas.height);
}
function doKleur(){
ctx.fillStyle = this.id;
}
function DoDown()
{
StartDraw = true;
}
function DoUp()
{
StartDraw = false;
}
function DoDot(x,y)
{
ctx.beginPath();
ctx.arc(x, y, dikte, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
}
function DoMove(event)
{
if(StartDraw)
{
DoDot(event.offsetX, event.offsetY)
}
}
</script>
<style>
canvas
{
border: solid 5px red;
border-radius: 15px;
}
</style>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<canvas id="canvas" width="1000" height="650"></canvas>
<input class="kleur" type="button" id="blue" value="blauw">
<input class="kleur" type="button" id="green" value="groen">
<input class="kleur" type="button" id="red" value="rood">
<input class="kleur" type="button" id="black" value="zwart">
<input class="kleur" type="button" id="orange" value="oranje">
<input type="button" class="clear" value="clear">
<input type="range" id="dikte" min="1" max="35" value="7">
</body>
</html>
You need to check when the mouse has just been clicked, is being held, when it released, or is just a quick click. You need to draw line segments when the mouse is being dragged, or just a point if its a quick click.
I prefer to bundle all my mouse events into one function and I create an abstract mouse object that I then use for whatever needs I have.
When I handle a mouse event, be that a move or click, whatever it is the last thing I do is save the button state. That means that next time the mouse event is called I know by checking the last and current mouse button state if the button was just clicked, is being held, or just up. You may say that the mousedown and mouseup events do that for you already, and yes they do and there is no reason for you not to use them. I just find it easier in the long run, as I can manipulate the mouse state.
So then when the mouse first goes down, record the coordinates, then when the mouse moves, draw a line from the last coordinate to the new one. When the mouse button goes up then do a quick check to see if it is just a point to draw and draw it if so, else do nothing.
Here is an example. The mouse code is at the bottom with mouse.buttonRaw being a bit field of the current mouse button state where first bit is left, second is middle, and third is right.
var mouse;
document.body.innerHTML = "Use mouse to draw on the this snippet.";
var demo = function(){
var canvas = (function(){
var canvas = document.getElementById("canv");
if(canvas !== null){
document.body.removeChild(canvas);
}
// creates a blank image with 2d context
canvas = document.createElement("canvas");
canvas.id = "canv";
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.style.position = "absolute";
canvas.style.top = "0px";
canvas.style.left = "0px";
canvas.style.zIndex = 1000;
canvas.ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
return canvas;
})();
var ctx = canvas.ctx;
if(mouse !== undefined){ // if the mouse exists
mouse.removeMouse(); // remove previous events
}
var canvasMouseCallBack = undefined; // if needed
// my mouse handler has more functionality than needed but to lazy to clean it ATM
mouse = (function(){
var mouse = {
x : 0,
y : 0,
w : 0,
alt : false,
shift : false,
ctrl : false,
interfaceId : 0,
buttonLastRaw : 0,
buttonRaw : 0,
over : false, // mouse is over the element
bm : [1, 2, 4, 6, 5, 3], // masks for setting and clearing button raw bits;
getInterfaceId : function () { return this.interfaceId++; }, // For UI functions
startMouse:undefined,
mouseEvents : "mousemove,mousedown,mouseup,mouseout,mouseover,mousewheel,DOMMouseScroll".split(",")
};
function mouseMove(e) {
var t = e.type, m = mouse;
m.x = e.offsetX;
m.y = e.offsetY;
if (m.x === undefined) { m.x = e.clientX; m.y = e.clientY; }
m.alt = e.altKey;
m.shift = e.shiftKey;
m.ctrl = e.ctrlKey;
if (t === "mousedown") { m.buttonRaw |= m.bm[e.which-1];
} else if (t === "mouseup") { m.buttonRaw &= m.bm[e.which + 2];
} else if (t === "mouseout") { m.buttonRaw = 0; m.over = false;
} else if (t === "mouseover") { m.over = true;
} else if (t === "mousewheel") { m.w = e.wheelDelta;
} else if (t === "DOMMouseScroll") { m.w = -e.detail;}
// call mouse callback if set
if (canvasMouseCallBack) { canvasMouseCallBack(mouse); }
e.preventDefault();
}
// function to add events to element
function startMouse(element){
if(element === undefined){
element = document;
}
mouse.element = element;
mouse.mouseEvents.forEach(
function(n){
element.addEventListener(n, mouseMove);
}
);
element.addEventListener("contextmenu", function (e) {e.preventDefault();}, false);
}
// function to remove events
mouse.removeMouse = function(){
if(mouse.element !== undefined){
mouse.mouseEvents.forEach(
function(n){
mouse.element.removeEventListener(n, mouseMove);
}
);
canvasMouseCallBack = undefined;
}
}
mouse.mouseStart = startMouse;
return mouse;
})();
// if there is a canvas add the mouse event else add to document
if(typeof canvas !== "undefined"){
mouse.mouseStart(canvas);
}else{
mouse.mouseStart();
}
// for the previouse mouse state
var lastMouseButton = 0;
var x,y,xx,yy; //for saving line segments drawn
// set up drawing
ctx.fillStyle = "red";
ctx.strokeStyle = "red";
ctx.lineWidth = 10;
ctx.lineJoin = "round";
ctx.lineCap = "round";
// set the mouse callback function. It is called for every mouse event
canvasMouseCallBack = function(mouse){
// is the first (left) button down and the last button state up?
if((mouse.buttonRaw & 1) === 1 && (lastMouseButton & 1) === 0){
x = mouse.x; // save the mouse coordinates
y = mouse.y;
}else
// is both the mouse button down and the last one down
if((mouse.buttonRaw & 1) === 1 && (lastMouseButton & 1) === 1){
xx = x; // yes move the last coordinate to the
yy = y; // start of the line segment
x = mouse.x; // get the mouse coords for the end of the line seg
y = mouse.y;
ctx.beginPath(); // draw the line segment
ctx.moveTo(x,y);
ctx.lineTo(xx,yy);
ctx.stroke();
}else
// has the mouse just been released
if( (mouse.buttonRaw & 1) === 0 && (lastMouseButton & 1) === 1){
if(xx === undefined){ // if xx is undefined then no line segment
// has been drawn so need to ad just a point
ctx.beginPath(); // draw a point at the last mouse point
ctx.arc(x,y,5,0,Math.PI*2);
ctx.fill();
}
xx = undefined; // clear the line segment start
}
// save the last mouse start
lastMouseButton = mouse.buttonRaw;
}
}
// resize demo to fit window if needed
window.addEventListener("resize",demo);
// start the demo
demo();
You may also be interested in this answer that deals with drawing as well but demonstrates how to smooth a line being draw as the mouse input can be very dirty.
Smooth a line
Related
I'm trying to do my Paint-like using HTML 5 Canvas. I have to do two type of rectangle: filled and not filled. Here's how I did that:
function rectangle(state = false) {
var first = [];
var second = [];
var click = 0;
canvas.mousedown(function(e) {
if (status == "rectangle") {
if (click == 0) {
first[0] = e.offsetX;
first[1] = e.offsetY;
click++;
} else {
second[0] = e.offsetX;
second[1] = e.offsetY;
if (state) {
ctx.fillRect(
first[0],
first[1],
second[0] - first[0],
second[1] - first[1]
);
} else {
ctx = canvas[0].getContext("2d");
ctx.strokeRect(
first[0],
first[1],
second[0] - first[0],
second[1] - first[1]
);
}
click = 0;
}
}
});
}
and this is my call
//rectangle ;)
$("#fill").click(function() {
$("#alert").text("fill Rectangle");
status = "rectangle";
rectangle(true);
});
$("#contour").click(function() {
$("#alert").text("Rectangle");
status = "rectangle";
rectangle();
});
I have 2 buttons for choosing which type of rectangle the user wants.
When I click on filled I can draw my rectangle like I want but when I switch to not filled, it still draws by filling the rectangle. For drawing a not filled rectangle I have to press F5 and click first in not filled.
Your problem is you're adding a new event listener each time the fill checkbox is modified, but not removing the old listener. This means you're drawing both the outline-rect and the filled-rect. Instead, only add a single event listener and handle state indide it.
Additional notes:
Firstly, you don't have to recreate a new context each click.
Secondly, you have a lot of repeated code
Thirdly, use {x, y} instead of [x, y] for future ease of modification.
let shape = 'rectangle'
let fill = false;
let clicks = [], clickCount = 0;
let fillCheck = document.querySelector('input');
fillCheck.addEventListener('input', () => fill = fillCheck.checked);
let canvas = document.querySelector('canvas');
let ctx = canvas.getContext("2d");
canvas.addEventListener('mousedown', e => {
if (shape == 'rectangle') {
clicks[clickCount++] = {x: e.offsetX, y: e.offsetY};
if (clickCount === 2) {
ctx[fill ? 'fillRect' : 'strokeRect'](
clicks[0].x,
clicks[0].y,
clicks[1].x - clicks[0].x,
clicks[1].y - clicks[0].y);
clickCount = 0;
}
}
});
canvas {
outline: 1px solid;
}
<div><label><input type="checkbox">Fill?</label></div>
<canvas width="300" height="300"></canvas>
Whenever I try to clear the canvas using clearRect(), at first it is cleared. But as soon as I start redrawing the old elements reappear. I even tried
context.width = context.width
but nothing seems to be working. The canvas is getting cleared initially but on clicking the clear button, it clears at first, but everything reappears. Please help me in debugging this error. The clearRect method is in the end of the code.
Below is the code
<script>
var canv = document.getElementById('canv'),
ctx = canv.getContext('2d'),
rect = [],
move = false;
var newRect;
var startX, startY, mouseX, mouseY;
var offsetX,offsetY;
function reOffset(){
var bound = canv.getBoundingClientRect();
offsetX = bound.left;
offsetY = bound.top;
}
reOffset();
function movement(){
canv.addEventListener('mousedown', mouseDown, false);
canv.addEventListener('mouseup', mouseUp, false);
canv.addEventListener('mousemove', mouseMove, false);
}
function mouseDown(event){
startX=parseInt(event.clientX-offsetX);
startY=parseInt(event.clientY-offsetY);
move = true;
}
function mouseUp(event){
mouseX=parseInt(event.clientX-offsetX);
mouseY=parseInt(event.clientY-offsetY);
move = false;
if(!overlap(newRect)){
rect.push(newRect);
}
make();
//ctx.fillRect(q.left,q.top,q.right-q.left,q.bottom-q.top);
}
function make(){
for(var i = 0; i < rect.length; i++){
var q = rect[i];
ctx.fillStyle = randomColour();
ctx.fillRect(q.left, q.top, q.right - q.left, q.bottom - q.top);
}
}
function mouseMove(event){
if(move){
mouseX=parseInt(event.clientX - offsetX);
mouseY=parseInt(event.clientY - offsetY);
newRect = {
left : Math.min(startX , mouseX),
right : Math.max(startX , mouseX),
top : Math.min(startY , mouseY),
bottom : Math.max(startY , mouseY),
}
ctx.clearRect(0, 0, canv.width, canv.height);
ctx.strokeRect(startX, startY, mouseX-startX, mouseY-startY);
}
}
function randomColour() {
var colour = [];
for (var i = 0; i < 3; i++) {
colour.push(Math.floor(Math.random() * 256));
}
return 'rgb(' + colour.join(',') + ')';
}
function overlap(newRect){
var q1 = newRect;
//if one rect is completely inside another rect
var inside = function(rectx, recty){
return(recty.left >= rectx.left &&
recty.right <= rectx.right &&
recty.top >= rectx.top &&
recty.bottom <= rectx.bottom);
}
//if the new rect is overlapping any existing rect
var isOverlaping = false;
for(var i = 0; i < rect.length; i++){
var q2 = rect[i];
var isIntersecting = !(q1.left > q2.right ||
q1.right < q2.left ||
q1.top > q2.bottom ||
q1.bottom < q2.top);
var isContain = inside(q2, q1) || inside(q1, q2);
if(isIntersecting || isContain){
isOverlaping=true;
}
}
return(isOverlaping);
}
movement();
//clear the canvas for redrawing
document.getElementById('clear').addEventListener('click', function () {
ctx.clearRect(0, 0, canv.width, canv.height);
}, false);
</script>`
<head>
<title>Simple Paint App</title>
</head>
<body>
<canvas id ="canv" width="1000" height="600" ></canvas>
<div id="button" style="position: absolute;">
<input type="button" id="clear" value="Clear">
</div>
</body>
You need to reset the rect array as well.
Adding this to your clear callback function:
document.getElementById('clear').addEventListener('click', function () {
rect = [];
console.log(rect);
ctx.clearRect(0, 0, canv.width, canv.height);
}, false);
should work, while removing the reset of the rect array (as in your clear callback function), logs the old rectangles as well.
What I mean is that the user presses a mouse button at point xy on an HTML canvas and while the mouse button is pressed the rectangle can be resized according to the movement of the cursor with point xy fixed. Like how highlighting works.
This is what I've got so far but it doesn't seem to be working:
canvas.addEventListener('mousedown', function(e){
var rectx = e.clientX;
var recty = e.clientY;
canvas.onmousemove = function(e){
var df = e.clientX;
var fg = e.clientY;
};
context.rect(rectx, recty, df-rectx, fg-recty);
context.stroke();
}, false);
Assuming there are no transforms (scale, translate) on your canvas context.
Basic steps for having a resizable rectangle are as follows:
Create a mousedown listener that sets a flag indicating the use is holding down the mouse button, as well as sets the "anchor," or initial coordinates.
Create a mouseup listener that unsets the flag.
Create a mousemove listener that, if the flag indicates the mouse is down, redraws the canvas with the rectangle's size changed according to mouse coordinates.
An important note is that client coordinates in the event object are relative to the page, not to your canvas element. You will frequently need to convert clientX and clientY into canvas coordinates:
var getCanvasCoords = function (clientX, clientY) {
var rect = canvas.getBoundingClientRect();
return {
x: clientX - rect.left,
y: clientY - rect.top
};
};
The first two steps look something like this:
var anchorX;
var anchorY;
var mouseDown = false;
canvas.addEventListener('mousedown', function (event) {
var coords = getCanvasCoords(event.clientX, event.clientY);
anchorX = coords.x;
anchorY = coords.y;
mouseDown = true;
});
canvas.addEventListener('mouseup', function (event) {
mouseDown = false;
});
And the mousemove handler:
canvas.addEventListener('mousemove', function (event) {
var coords = getCanvasCoords(event.clientX, event.clientY);
var width = coords.x - anchorX;
var height = coords.y - anchorY;
// clear canvas for redrawing
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(anchorX, anchorY, width, height);
});
Don't Render from mouse events!
The given answer is correct but it is not the best way to do this.
The are two reasons. First the mousemove event can fire up to 600+ times a second but the display only refreshes 60 times a second. Rendering from the input event is many time just a waste of CPU time as the results will be overwritten by the next mouse event before it is ever had a chance to be displayed.
The second reason is that dedicating an event listener to a single task makes it hard to add more functionality. You end up adding more and more code to the mousemove event to handle all the types of input, most of which can be ignored because of the high update speed of the mouse.
Mouse listeners
Mouse event listeners do the minimum possible. They just record the mouse state and no more. Also all mouse events return the mouse position. You should not ignore the mouse position for events like mouse down and up
The following function creates a mouse object for a element. The mouse object has the x,y position relative to the to left of the element, and the current button states for 3 buttons it is left to right button1, button2, button3.
Also when the mouse leaves the element and then releases the mouse button the mouse for the element will not see the mouseup event and not know the mouse button is up. To prevent the mouse buttons from getting stuck you turn off the buttons when the mouse leaves the element.
The best mouse listener is to the whole page as it can track mouse events that happen even when the mouse is outside the window/tab (if the window/tab has focus), but that is a little to complex for this answer.
Function to create a mouse for an element
function createMouse(element){
var mouse = {
x : 0,
y : 0,
button1 : false,
button2 : false,
button3 : false,
over : false,
};
function mouseEvent(event){
var bounds = element.getBoundingClientRect();
mouse.x = event.pageX - bounds.left - scrollX;
mouse.y = event.pageY - bounds.top - scrollY;
if(event.type === "mousedown"){
mouse["button"+event.which] = true;
} else if(event.type === "mouseup"){
mouse["button"+event.which] = false;
} else if(event.type === "mouseover"){
mouse.over = true;
} else if(event.type === "mouseout"){
mouse.over = false;
mouse.button1 = false; // turn of buttons to prevent them locking
mouse.button2 = false;
mouse.button3 = false;
}
event.preventDefault(); // stops default mouse behaviour.
}
var events = "mousemove,mousedown,mouseup,mouseout,mouseover".split(',');
events.forEach(eventType => element.addEventListener(eventType,mouseEvent));
mouse.remove = function(){
events.forEach(eventType => element.removeEventListener(eventType, mouseEvent));
}
return mouse;
}
Using the mouse
It is now just a matter of creating a mouse for the element
var canMouse = createMouse(canvas);
And then in your main render loop do the dragging.
var drag = {
x : 0,
y : 0,
x1 : 0,
y1 : 0,
dragging : false,
top : 0,
left : 0,
width : 0,
height : 0,
}
function mainLoop(){
if(canMouse.button1){ // is button down
if(!drag.dragging){ // is dragging
drag.x = canMouse.x;
drag.y = canMouse.y;
drag.dragging = true;
}
drag.x1 = canMouse.x;
drag.y1 = canMouse.y;
drag.top = Math.min(drag.y, drag.y1);
drag.left = Math.min(drag.x, drag.x1);
drag.width = Math.abs(drag.x - drag.x1);
drag.height = Math.abs(drag.y - drag.y1);
}else{
if(drag.dragging){
drag.dragging = false;
}
}
}
Putting it all together
function createMouse(element){
var mouse = {
x : 0,
y : 0,
button1 : false,
button2 : false,
button3 : false,
over : false,
};
function mouseEvent(event){
var bounds = element.getBoundingClientRect();
// NOTE getting the border should not be done like this as
// it will not work in all cases.
var border = Number(element.style.border.split("px")[0])
mouse.x = event.pageX - bounds.left - scrollX - border;
mouse.y = event.pageY - bounds.top - scrollY - border;
if(event.type === "mousedown"){
mouse["button"+event.which] = true;
} else if(event.type === "mouseup"){
mouse["button"+event.which] = false;
} else if(event.type === "mouseover"){
mouse.over = true;
} else if(event.type === "mouseout"){
mouse.over = false;
mouse.button1 = false; // turn of buttons to prevent them locking
mouse.button2 = false;
mouse.button3 = false;
}
event.preventDefault(); // stops default mouse behaviour.
}
var events = "mousemove,mousedown,mouseup,mouseout,mouseover".split(',');
events.forEach(eventType => element.addEventListener(eventType,mouseEvent));
mouse.remove = function(){
events.forEach(eventType => element.removeEventListener(eventType, mouseEvent));
}
return mouse;
}
var drag = {
x : 0,
y : 0,
x1 : 0,
y1 : 0,
dragging : false,
top : 0,
left : 0,
width : 0,
height : 0,
}
var ctx = canvas.getContext("2d");
ctx.strokeStyle = "black";
ctx.lineWidth = 1;
var mouse = createMouse(canvas);
function update(){
ctx.clearRect(0,0,canvas.width,canvas.height);
if(mouse.button1){ // is button down
if(!drag.dragging){ // is dragging
drag.x = mouse.x;
drag.y = mouse.y;
drag.dragging = true;
}
drag.x1 = mouse.x;
drag.y1 = mouse.y;
drag.top = Math.min(drag.y, drag.y1);
drag.left = Math.min(drag.x, drag.x1);
drag.width = Math.abs(drag.x - drag.x1);
drag.height = Math.abs(drag.y - drag.y1);
}else{
if(drag.dragging){
drag.dragging = false;
}
}
if(drag.dragging){
ctx.strokeRect(drag.left, drag.top, drag.width, drag.height);
}
requestAnimationFrame(update);
}
requestAnimationFrame(update);
canvas {
border : 1px solid black;
}
Click drag to draw rectangle.<br>
<canvas id="canvas" width= "512" height = "256"></canvas>
I am trying to create a pannable image viewer which also allows magnification. If the zoom factor or the image size is such that the image no longer paints over the entire canvas then I wish to have the area of the canvas which does not contain the image painted with a specified background color.
My current implementation allows for zooming and panning but with the unwanted effect that the image leaves a tiled trail after it during a pan operation (much like the cards in windows Solitaire when you win a game). How do I clean up my canvas such that the image does not leave a trail and my background rectangle properly renders in my canvas?
To recreate the unwanted effect set magnification to some level at which you see the dark gray background show and then pan the image with the mouse (mouse down and drag).
Code snippet added below and Plnkr link for those who wish to muck about there.
http://plnkr.co/edit/Cl4T4d13AgPpaDFzhsq1
<!DOCTYPE html>
<html>
<head>
<style>
canvas{
border:solid 5px #333;
}
</style>
</head>
<body>
<button onclick="changeScale(0.10)">+</button>
<button onclick="changeScale(-0.10)">-</button>
<div id="container">
<canvas width="700" height="500" id ="canvas1"></canvas>
</div>
<script>
var canvas = document.getElementById('canvas1');
var context = canvas.getContext("2d");
var imageDimensions ={width:0,height:0};
var photo = new Image();
var isDown = false;
var startCoords = [];
var last = [0, 0];
var windowWidth = canvas.width;
var windowHeight = canvas.height;
var scale=1;
photo.addEventListener('load', eventPhotoLoaded , false);
photo.src = "http://www.html5rocks.com/static/images/cors_server_flowchart.png";
function eventPhotoLoaded(e) {
imageDimensions.width = photo.width;
imageDimensions.height = photo.height;
drawScreen();
}
function changeScale(delta){
scale += delta;
drawScreen();
}
function drawScreen(){
context.fillRect(0,0, windowWidth, windowHeight);
context.fillStyle="#333333";
context.drawImage(photo,0,0,imageDimensions.width*scale,imageDimensions.height*scale);
}
canvas.onmousedown = function(e) {
isDown = true;
startCoords = [
e.offsetX - last[0],
e.offsetY - last[1]
];
};
canvas.onmouseup = function(e) {
isDown = false;
last = [
e.offsetX - startCoords[0], // set last coordinates
e.offsetY - startCoords[1]
];
};
canvas.onmousemove = function(e)
{
if(!isDown) return;
var x = e.offsetX;
var y = e.offsetY;
context.setTransform(1, 0, 0, 1,
x - startCoords[0], y - startCoords[1]);
drawScreen();
}
</script>
</body>
</html>
You need to reset the transform.
Add context.setTransform(1,0,0,1,0,0); just before you clear the canvas and that will fix your problem. It sets the current transform to the default value. Then befor the image is draw set the transform for the image.
UPDATE:
When interacting with user input such as mouse or touch events it should be handled independently of rendering. The rendering will fire only once per frame and make visual changes for any mouse changes that happened during the previous refresh interval. No rendering is done if not needed.
Dont use save and restore if you don't need to.
var canvas = document.getElementById('canvas1');
var ctx = canvas.getContext("2d");
var photo = new Image();
var mouse = {}
mouse.lastY = mouse.lastX = mouse.y = mouse.x = 0;
mouse.down = false;
var changed = true;
var scale = 1;
var imageX = 0;
var imageY = 0;
photo.src = "http://www.html5rocks.com/static/images/cors_server_flowchart.png";
function changeScale(delta){
scale += delta;
changed = true;
}
// Turns mouse button of when moving out to prevent mouse button locking if you have other mouse event handlers.
function mouseEvents(event){ // do it all in one function
if(event.type === "mouseup" || event.type === "mouseout"){
mouse.down = false;
changed = true;
}else
if(event.type === "mousedown"){
mouse.down = true;
}
mouse.x = event.offsetX;
mouse.y = event.offsetY;
if(mouse.down) {
changed = true;
}
}
canvas.addEventListener("mousemove",mouseEvents);
canvas.addEventListener("mouseup",mouseEvents);
canvas.addEventListener("mouseout",mouseEvents);
canvas.addEventListener("mousedown",mouseEvents);
function update(){
requestAnimationFrame(update);
if(photo.complete && changed){
ctx.setTransform(1,0,0,1,0,0);
ctx.fillStyle="#333";
ctx.fillRect(0,0, canvas.width, canvas.height);
if(mouse.down){
imageX += mouse.x - mouse.lastX;
imageY += mouse.y - mouse.lastY;
}
ctx.setTransform(scale, 0, 0, scale, imageX,imageY);
ctx.drawImage(photo,0,0);
changed = false;
}
mouse.lastX = mouse.x
mouse.lastY = mouse.y
}
requestAnimationFrame(update);
canvas{
border:solid 5px #333;
}
<button onclick="changeScale(0.10)">+</button><button onclick="changeScale(-0.10)">-</button>
<canvas width="700" height="500" id ="canvas1"></canvas>
Nice Code ;)
You are seeing the 'tiled' effect in your demonstration because you are painting the scaled image to the canvas on top of itself each time the drawScreen() function is called while dragging. You can rectify this in two simple steps.
First, you need to clear the canvas between calls to drawScreen() and second, you need to use the canvas context.save() and context.restore() methods to cleanly reset the canvas transform matrix between calls to drawScreen().
Given your code as is stands:
Create a function to clear the canvas. e.g.
function clearCanvas() {
context.clearRect(0, 0, canvas.width, canvas.height);
}
In the canavs.onmousemove() function, call clearCanvas() and invoke context.save() before redefining the transform matrix...
canvas.onmousemove = function(e) {
if(!isDown) return;
var x = e.offsetX;
var y = e.offsetY;
/* !!! */
clearCanvas();
context.save();
context.setTransform(
1, 0, 0, 1,
x - startCoords[0], y - startCoords[1]
);
drawScreen();
}
... then conditionally invoke context.restore() at the end of drawScreen() ...
function drawScreen() {
context.fillRect(0,0, windowWidth, windowHeight);
context.fillStyle="#333333";
context.drawImage(photo,0,0,imageDimensions.width*scale,imageDimensions.height*scale);
/* !!! */
if (isDown) context.restore();
}
Additionally, you may want to call clearCanvas() before rescaling the image, and the canvas background could be styled with CSS rather than .fillRect() (in drawScreen()) - which could give a performance gain on low spec devices.
Edited in light of comments from Blindman67 below
See Also
Canvas.context.save : https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/save
Canvas.context.restore : https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/restore
requestAnimationFrame : https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame
Paul Irish, requestAnimationFrame polyfill : http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
Call context.save to save the transformation matrix before you call context.fillRect.
Then whenever you need to draw your image, call context.restore to restore the matrix.
For example:
function drawScreen(){
context.save();
context.fillStyle="#333333";
context.fillRect(0,0, windowWidth, windowHeight);
context.restore();
context.drawImage(photo,0,0,imageDimensions.width*scale,imageDimensions.height*scale);
}
Also, to further optimize, you only need to set fillStyle once until you change the size of canvas.
i am new in html5 , i want to create a event listener on my mouse , i have written the following code , but cannot understand y , i cant create the event listener on my canvas element , kindly help
var canvasDiv = document.getElementById('canvas');
canvas_simple = document.createElement('canvas');
canvas_simple.setAttribute('height', canvasHeight);
canvas_simple.setAttribute('id', 'canvasSimple');
canvasDiv.appendChild(canvas_simple);
if(typeof G_vmlCanvasManager != 'undefined')
{
canvas_simple = G_vmlCanvasManager.initElement(canvas_simple);
}
context_simple = canvas_simple.getContext("2d");
context_simple.addEventListener('mousemove', ev_mousemove, false);
in light of a ans i want give me event listener code also , may be it has a error also
var started = false;
function ev_mousemove (ev) {
var x, y;
if (ev.layerX || ev.layerX == 0) { // Firefox
x = ev.layerX;
y = ev.layerY;
}
else if (ev.offsetX || ev.offsetX == 0) { // Opera
x = ev.offsetX;
y = ev.offsetY;
}
if (!started) {
context.beginPath();
context.moveTo(x, y);
started = true;
}
else {
context.strokeStyle = "#df4b26";
context.lineJoin = "round";
context.lineWidth = 10;
context.lineTo(x, y);
context.stroke();
}
}
You want to add the event to your canvas, not the 2d context:
canvas_simple.addEventListener('mousemove', ev_mousemove, false);
Here is a demo: jsFiddle link
There are a few mistakes:
You cannot attach the listener to the context, listeners can only be attached to: a single node in a document, the document itself, a window, or an XMLHttpRequest. So you should attach it to the canvas element.
You cannot nest canvas
The canvasHeight property is not defined
I created a jsfiddle with your example modified and working --> here