Window.Onload function not firing in IE 10 - javascript

I am trying to create a zooming and panning app to work across all browsers. It works in all other browsers, but in IE 10- just doesn't load the image, but does redraw it when I click on canvas to zoom in. Here's the window.onload part of the code:
window.onload = function(){
var ctx = canvas.getContext('2d');
trackTransforms(ctx);
function redraw(){
ctx.save();
ctx.setTransform(1,0,0,1,0,0);
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.restore();
ctx.drawImage(map,0,0, canvas.width, canvas.height);
}
redraw();
var lastX=canvas.width/2, lastY=canvas.height/2;
var dragStart,dragged;
canvas.addEventListener('mousedown',function(evt){
document.body.style.mozUserSelect = document.body.style.webkitUserSelect = document.body.style.userSelect = 'none';
lastX = evt.offsetX || (evt.pageX - canvas.offsetLeft);
lastY = evt.offsetY || (evt.pageY - canvas.offsetTop);
dragStart = ctx.transformedPoint(lastX,lastY);
dragged = false;
},false);
canvas.addEventListener('mousemove',function(evt){
lastX = evt.offsetX || (evt.pageX - canvas.offsetLeft);
lastY = evt.offsetY || (evt.pageY - canvas.offsetTop);
dragged = true;
if (dragStart){
var pt = ctx.transformedPoint(lastX,lastY);
ctx.translate(pt.x-dragStart.x,pt.y-dragStart.y);
redraw();
}
},false);
canvas.addEventListener('mouseup',function(evt){
dragStart = null;
if (!dragged) zoom(evt.shiftKey ? -1 : 1 );
},false);
var scaleFactor = 1.1;
var zoom = function(clicks){
var pt = ctx.transformedPoint(lastX,lastY);
ctx.translate(pt.x,pt.y);
var factor = Math.pow(scaleFactor,clicks);
ctx.scale(factor,factor);
ctx.translate(-pt.x,-pt.y);
redraw();
}
var handleScroll = function(evt){
var delta = evt.wheelDelta ? evt.wheelDelta/40 : evt.detail ? -evt.detail : 0;
if (delta) zoom(delta);
return evt.preventDefault() && false;
};
canvas.addEventListener('DOMMouseScroll',handleScroll,false);
canvas.addEventListener('mousewheel',handleScroll,false);
};
map.src = 'http://www.theodora.com/maps/new9/time_zones_4.jpg';

Related

draw an rectangle on a pdf inside canvas using pdf.js

I should draw a rectangle inside a pdf document in canvas, but it cleans the background of document.
I want a way to draw a rectangle in it without cleaning the background. Please can anyone help me with this.
Below is the code i am using:
$("#div").mouseover(function () {
$("canvas").on('click', function (e) {
console.log(nr)
id = ($(this).attr("id"));
console.log(id)
const baseImage = loadImage("");
var canvas = document.getElementById(id);
var ctx = canvas.getContext('2d');
Canvas = ctx;
var canvasx = $(canvas).offset().left;
var canvasy = $(canvas).offset().top;
var last_mousex = last_mousey = 0;
var prev_x = prev_y = prev_w = prev_h = 0;
var mousex = mousey = 0;
var mousedown = false;
$(canvas).on('mousedown', function (e) {
if (rectanglearray.length < 2) {
last_mousex = parseInt(e.clientX - canvasx);
last_mousey = parseInt(e.clientY - canvasy);
mousedown = true;
}
});
$(canvas).on('mouseup', function (e) {
mousedown = false;
});
$(canvas).on('mousemove', function (e) {
mousex = parseInt(e.clientX - canvasx);
mousey = parseInt(e.clientY - canvasy);
if (mousedown) {
//if (rectanglearray.length < 2) {
ctx.clearRect(0, 0, canvas.width, canvas.height); //clear canvas
ctx.beginPath();
var width = mousex - last_mousex;
var height = mousey - last_mousey;
ctx.rect(last_mousex, last_mousey, width, height);
a = last_mousex;
b = last_mousey;
c = last_mousex + width;
d = last_mousey + height;
gjer = width;
lart = height;
t = a;
h = b;
gjere = gjer;
larte = lart;
nfq = id.substring(3, 4);
ctx.strokeStyle = 'black';
ctx.lineWidth = 1;
ctx.stroke();
rectanglearray.push(ctx);
//}
}
});
execute++;
});
});
so when i click in one of the pages of pdf it takes pages id and allows to only draw a rectangle in that page, but when i draw it cleans the background.

How to draw CIRCLE on canvas on mouse move

I'm trying to draw a circle on canvas on mouse move, but without success. My code is as follows:
var damages_canvas = document.getElementById('damages-area');
var ctx_damages = damages_canvas.getContext('2d');
var circle_rect = damages_canvas.getBoundingClientRect();
var circle_drag = false;
var circle_canvas_update = true;
var circles = [];
var markerColor = "#f00";
damages_canvas.addEventListener('mousedown', drawCircleMouseDown, false);
damages_canvas.addEventListener('mouseup', drawCircleMouseUp, false);
damages_canvas.addEventListener('mousemove', drawCircleMouseMove, false);
requestAnimationFrame(updateCircleCanvas);
function updateCircleCanvas(){
if(circle_canvas_update){
drawCircleCanvas();
circle_canvas_update = false;
}
requestAnimationFrame(updateCircleCanvas);
}
function drawCircle(circle){
var startX = circle.startX,
endX = circle.endX,
startY = circle.startY,
endY = circle.endY;
ctx_damages.clearRect(0,0,damages_canvas.width,damages_canvas.height);
ctx_damages.beginPath();
ctx_damages.moveTo(startX, startY + (endY-startY)/2);
ctx_damages.bezierCurveTo(startX, startY, endX, startY, endX, startY + (endX-startY)/2);
ctx_damages.bezierCurveTo(endX, endY, startX, endY, startX, startY + (endY-startY)/2);
ctx_damages.closePath();
ctx_damages.stroke();
}
function drawCircleCanvas(){
ctx_damages.setTransform(1,0,0,1,0,0);
ctx_damages.clearRect(0, 0, damages_canvas.width, damages_canvas.height);
ctx_damages.fillStyle = "transparent"; // Color
ctx_damages.strokeStyle = markerColor; // Color
circles.forEach(drawCircle)
}
function drawCircleMouseDown(e){
circle = {
startX : e.offsetX - circle_rect.left,
startY : e.offsetY - circle_rect.top,
endX : 10,
endY : 10
};
circle_drag = true;
circles.push(circle);
circle_canvas_update = true;
}
function drawCircleMouseUp(){
circle_drag = false;
circle_canvas_update = true;
}
function drawCircleMouseMove(e){
if(circle_drag){
circle.endX = e.offsetX - circle_rect.left;
circle.endY = e.offsetY - circle_rect.top;
circle_canvas_update = true;
}
}
#damages-area {background:#f9f9f9}
<canvas id="damages-area" width=600 height=600></canvas>
I want to draw a circle, not ellipsis or anything else. But in my case I get something strange.
Here is also the fiddle.
Any idea how can I do it?
Use arc to draw an arc in canvas. For circle start and end angles will be 0 and 2*Math.PI
var damages_canvas = document.getElementById('damages-area');
var ctx_damages = damages_canvas.getContext('2d');
var circles = [];
var markerColor = "#f00";
var offsetX = damages_canvas.offsetLeft;
var offsetY = damages_canvas.offsetTop;
var startX;
var startY;
var isMouseDown = false;
var circle, radius;
damages_canvas.addEventListener('mousedown', drawCircleMouseDown, false);
damages_canvas.addEventListener('mouseup', drawCircleMouseUp, false);
damages_canvas.addEventListener('mousemove', drawCircleMouseMove, false);
function Circle(startX, startY) {
this.startX = startX;
this.startY = startY;
this.radius;
this.draw = function() {
ctx_damages.beginPath();
ctx_damages.arc(this.startX, this.startY, this.radius, 0, 2 * Math.PI);
ctx_damages.strokeStyle = markerColor;
ctx_damages.stroke();
}
}
function drawCircleMouseDown(e) {
startX = parseInt(e.clientX - offsetX);
startY = parseInt(e.clientY - offsetY);
isMouseDown = true;
circle = new Circle(startX, startY);
circles.push(circle);
}
function drawCircleMouseUp() {
isMouseDown = false;
circle = null;
}
function drawCircleMouseMove(e) {
if (!isMouseDown) {
return;
}
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
circle.radius = getDistance(startX, startY, mouseX, mouseY);
ctx_damages.clearRect(0, 0, damages_canvas.width, damages_canvas.height);
circles.forEach(function(circ) {
circ.draw();
});
}
function getDistance(p1X, p1Y, p2X, p2Y) {
return Math.sqrt(Math.pow(p1X - p2X, 2) + Math.pow(p1Y - p2Y, 2))
}
#damages-area {background:#f9f9f9}
<canvas id="damages-area" width=600 height=600></canvas>
These changes:
var b=0.55191502449;
var damages_canvas = document.getElementById("damages-area");
var ctx_damages = damages_canvas.getContext("2d");
var circle_rect = damages_canvas.getBoundingClientRect();
var circles = [];
var markerColor = "#f00";
var circle_drag = false;
var circle_canvas_update = true;
damages_canvas.addEventListener('mousedown', drawCircleMouseDown, false);
damages_canvas.addEventListener('mouseup', drawCircleMouseUp, false);
damages_canvas.addEventListener('mousemove', drawCircleMouseMove, false);
requestAnimationFrame(updateCircleCanvas);
function updateCircleCanvas(){
if(circle_canvas_update){
drawCircleCanvas();
circle_canvas_update = false;
}
requestAnimationFrame(updateCircleCanvas);
}
function drawCircle(circle){
var k=circle.firstk,siiry= circle.startY,siirx= circle.startX;
ctx_damages.clearRect(0,0,damages_canvas.width,damages_canvas.height);
ctx_damages.beginPath();
ctx_damages.moveTo(0*k+siirx, 1*k+siiry);
ctx_damages.bezierCurveTo(b*k+siirx, 1*k+siiry, 1*k+siirx, b*k+siiry,
1*k+siirx, 0+siiry);
ctx_damages.moveTo(0*k-(2*0*k)+siirx, 1*k-(2*1*k)+siiry);
ctx_damages.bezierCurveTo(b*k-(2*b*k)+siirx, 1*k-(2*1*k)+siiry, 1*k-
(2*1*k)+siirx, b*k-(2*b*k)+siiry, 1*k-(2*1*k)+siirx, 0-(2*0)+siiry);
ctx_damages.moveTo(0*k+siirx, 1*k+siiry);
ctx_damages.bezierCurveTo(b*k-(2*b*k)+siirx, 1*k+siiry, 1*k-(2*1*k)+siirx,
b*k+siiry, 1*k-(2*1*k)+siirx, 0-(2*0)+siiry);
ctx_damages.moveTo(0*k-(2*0*k)+siirx, 1*k-(2*1*k)+siiry);
ctx_damages.bezierCurveTo(b*k+siirx, 1*k-(2*1*k)+siiry, 1*k+siirx, b*k-
(2*b*k)+siiry, 1*k+siirx, 0+siiry);
ctx_damages.stroke();
}
function drawCircleMouseDown(e){
circle = {
startX : e.offsetX - circle_rect.left,
startY : e.offsetY - circle_rect.top,
firstk : 10
};
circle_drag = true;
circles.push(circle);
circle_canvas_update = true;
}
function drawCircleCanvas(){
ctx_damages.setTransform(1,0,0,1,0,0);
ctx_damages.clearRect(0, 0, damages_canvas.width, damages_canvas.height);
ctx_damages.fillStyle = "transparent"; // Color
ctx_damages.strokeStyle = markerColor; // Color
circles.forEach(drawCircle)
}
function drawCircleMouseUp(){
circle_drag = false;
circle_canvas_update = true;
}
function drawCircleMouseMove(e){ // tätä uusi
if(circle_drag){
console.log(e.offsetX -circle.startX );
circle.firstk =Math.hypot((e.offsetX -circle.startX),(e.offsetY -
circle.startY))
circle_canvas_update = true;
}
}
I jsfidle this https://jsfiddle.net/narutofanforewe/u13ujcrL/1/
Check my blog too http://www.thenew3d.website/2018/02/28/bezier-circle/

Extend javascript to use multiple canvas boxes

I have very little knowledge of javascript, sadly. I'm at the moment working on a script. I want to sign files online, possible with any kind of touchscreen. I've got a script online that delivers a little canvas box with signing-functionality. Sadly my javascript skills are too bad to use it the way I want.
var isSign = false;
var leftMButtonDown = false;
jQuery(function(){
//Initialize sign pad
init_Sign_Canvas();
});
function fun_submit() {
if(isSign) {
var canvas = $("#canvas").get(0);
var imgData = canvas.toDataURL();
jQuery('#page').find('p').remove();
jQuery('#page').find('img').remove();
jQuery('#page').append(jQuery('<p>Your Sign:</p>'));
jQuery('#page').append($('<img/>').attr('src',imgData));
closePopUp();
} else {
alert('Please sign');
}
}
function closePopUp() {
jQuery('#divPopUpSignContract').popup('close');
jQuery('#divPopUpSignContract').popup('close');
}
function init_Sign_Canvas() {
isSign = false;
leftMButtonDown = false;
//Set Canvas width
var sizedWindowWidth = $(window).width();
if(sizedWindowWidth > 700)
sizedWindowWidth = $(window).width() / 2;
else if(sizedWindowWidth > 400)
sizedWindowWidth = sizedWindowWidth - 100;
else
sizedWindowWidth = sizedWindowWidth - 50;
$("#canvas").width(200);
$("#canvas").height(50);
$("#canvas").css("border","1px solid #000");
var canvas = $("#canvas").get(0);
canvasContext = canvas.getContext('2d');
if(canvasContext)
{
canvasContext.canvas.width = 200;
canvasContext.canvas.height = 50;
canvasContext.fillStyle = "#fff";
canvasContext.fillRect(0,0,sizedWindowWidth,200);
canvasContext.moveTo(50,150);
canvasContext.lineTo(sizedWindowWidth-50,150);
canvasContext.stroke();
canvasContext.fillStyle = "#000";
canvasContext.font="20px Arial";
canvasContext.fillText("x",40,155);
}
// Bind Mouse events
$(canvas).on('mousedown', function (e) {
if(e.which === 1) {
leftMButtonDown = true;
canvasContext.fillStyle = "#000";
var x = e.pageX - $(e.target).offset().left;
var y = e.pageY - $(e.target).offset().top;
canvasContext.moveTo(x, y);
}
e.preventDefault();
return false;
});
$(canvas).on('mouseup', function (e) {
if(leftMButtonDown && e.which === 1) {
leftMButtonDown = false;
isSign = true;
}
e.preventDefault();
return false;
});
// draw a line from the last point to this one
$(canvas).on('mousemove', function (e) {
if(leftMButtonDown == true) {
canvasContext.fillStyle = "#000";
var x = e.pageX - $(e.target).offset().left;
var y = e.pageY - $(e.target).offset().top;
canvasContext.lineTo(x,y);
canvasContext.stroke();
}
e.preventDefault();
return false;
});
//bind touch events
$(canvas).on('touchstart', function (e) {
leftMButtonDown = true;
canvasContext.fillStyle = "#000";
var t = e.originalEvent.touches[0];
var x = t.pageX - $(e.target).offset().left;
var y = t.pageY - $(e.target).offset().top;
canvasContext.moveTo(x, y);
e.preventDefault();
return false;
});
$(canvas).on('touchmove', function (e) {
canvasContext.fillStyle = "#000";
var t = e.originalEvent.touches[0];
var x = t.pageX - $(e.target).offset().left;
var y = t.pageY - $(e.target).offset().top;
canvasContext.lineTo(x,y);
canvasContext.stroke();
e.preventDefault();
return false;
});
$(canvas).on('touchend', function (e) {
if(leftMButtonDown) {
leftMButtonDown = false;
isSign = true;
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas">Canvas is not supported</canvas>
I need 3 canvas boxes, that can be signed parallel to each other. Is it possible to give me a hint or a tutorial or something that will make me understand what I need to change?
Not quite sure if this is what you mean (maybe three independent sign-in boxes?).
Use 3 HTML5 <canvas> elements, and initialize them. Then use the drawImage() function to copy the first canvas image onto the canvas context of the other two.
var isSign = false;
var leftMButtonDown = false;
jQuery(function(){
//Initialize sign pad
init_Sign_Canvas();
});
function fun_submit() {
if(isSign) {
var canvas = $("#canvas").get(0);
var imgData = canvas.toDataURL();
jQuery('#page').find('p').remove();
jQuery('#page').find('img').remove();
jQuery('#page').append(jQuery('<p>Your Sign:</p>'));
jQuery('#page').append($('<img/>').attr('src',imgData));
closePopUp();
} else {
alert('Please sign');
}
}
function closePopUp() {
jQuery('#divPopUpSignContract').popup('close');
jQuery('#divPopUpSignContract').popup('close');
}
function init_Sign_Canvas() {
isSign = false;
leftMButtonDown = false;
//Set Canvas width
var sizedWindowWidth = $(window).width();
if(sizedWindowWidth > 700)
sizedWindowWidth = $(window).width() / 2;
else if(sizedWindowWidth > 400)
sizedWindowWidth = sizedWindowWidth - 100;
else
sizedWindowWidth = sizedWindowWidth - 50;
$("#canvas").width(200);
$("#canvas").height(50);
$("#canvas").css("border","1px solid #000");
$("#canvas2").width(200);
$("#canvas2").height(50);
$("#canvas2").css("border","1px solid #000");
$("#canvas3").width(200);
$("#canvas3").height(50);
$("#canvas3").css("border","1px solid #000");
var canvas = $("#canvas").get(0);
var canvas2 = $("#canvas2").get(0);
var canvas3 = $("#canvas3").get(0);
canvasContext = canvas.getContext('2d');
canvas2ctx = canvas2.getContext('2d');
canvas3ctx = canvas3.getContext('2d');
if(canvasContext)
{
canvasContext.canvas.width = 200;
canvasContext.canvas.height = 50;
canvas2ctx.canvas.width = 200;
canvas2ctx.canvas.height = 50;
canvas3ctx.canvas.width = 200;
canvas3ctx.canvas.height = 50;
canvasContext.fillStyle = "#fff";
canvasContext.fillRect(0,0,sizedWindowWidth,200);
canvasContext.moveTo(50,150);
canvasContext.lineTo(sizedWindowWidth-50,150);
canvasContext.stroke();
canvasContext.fillStyle = "#000";
canvasContext.font="20px Arial";
canvasContext.fillText("x",40,155);
}
// Bind Mouse events
$(canvas).on('mousedown', function (e) {
if(e.which === 1) {
leftMButtonDown = true;
canvasContext.fillStyle = "#000";
var x = e.pageX - $(e.target).offset().left;
var y = e.pageY - $(e.target).offset().top;
canvasContext.moveTo(x, y);
}
e.preventDefault();
return false;
});
$(canvas).on('mouseup', function (e) {
if(leftMButtonDown && e.which === 1) {
leftMButtonDown = false;
isSign = true;
canvas2ctx.drawImage(canvas,0,0);
canvas3ctx.drawImage(canvas,0,0);
}
e.preventDefault();
return false;
});
// draw a line from the last point to this one
$(canvas).on('mousemove', function (e) {
if(leftMButtonDown == true) {
canvasContext.fillStyle = "#000";
var x = e.pageX - $(e.target).offset().left;
var y = e.pageY - $(e.target).offset().top;
canvasContext.lineTo(x,y);
canvasContext.stroke();
}
e.preventDefault();
return false;
});
//bind touch events
$(canvas).on('touchstart', function (e) {
leftMButtonDown = true;
canvasContext.fillStyle = "#000";
var t = e.originalEvent.touches[0];
var x = t.pageX - $(e.target).offset().left;
var y = t.pageY - $(e.target).offset().top;
canvasContext.moveTo(x, y);
e.preventDefault();
return false;
});
$(canvas).on('touchmove', function (e) {
canvasContext.fillStyle = "#000";
var t = e.originalEvent.touches[0];
var x = t.pageX - $(e.target).offset().left;
var y = t.pageY - $(e.target).offset().top;
canvasContext.lineTo(x,y);
canvasContext.stroke();
e.preventDefault();
return false;
});
$(canvas).on('touchend', function (e) {
if(leftMButtonDown) {
leftMButtonDown = false;
isSign = true;
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas">Canvas is not supported</canvas>
<canvas id="canvas2">Canvas is not supported</canvas>
<canvas id="canvas3">Canvas is not supported</canvas>

JavaScript Canvas on draw vanishes

I have a canvas function which draws a square if I click on the canvas field and move the mouse, that works so far.
My Problem is that if I release the mouse and click at the canvas again the old drawn rectangle vanishes.
How do I make it possible that the old drawn does not get vanished.
My function:
function foo() {
var tool = this;
this.started = false;
var canvasx = canvas.offsetLeft;
var canvasy = canvas.offsetTop;
var last_mousex = 0;
var last_mousey = 0;
var mousex = 0;
var mousey = 0;
this.mousedown = function (ev) {
if(checkboxSquare.checked) {
last_mousex = parseInt(ev.clientX-canvasx);
last_mousey = parseInt(ev.clientY-canvasy);
context.strokeStyle = $('#selectColor').val();
context.lineWidth = $('#selectWidth').val();
tool.started = true;
}
};
this.mousemove = function (ev) {
if (tool.started && checkboxSquare.checked) {
mousex = parseInt(ev.clientX-canvasx);
mousey = parseInt(ev.clientY-canvasy);
context.clearRect(0, 0, canvas.width, canvas.height); // clear canvas
context.beginPath();
var width = mousex-last_mousex;
var height = mousey-last_mousey;
context.rect(last_mousex,last_mousey,width,height);
context.stroke();
}
};
this.mouseup = function (ev) {
if (tool.started && checkboxSquare.checked) {
tool.mousemove(ev);
tool.started = false;
}
};
}
It Looks something like this: http://jsfiddle.net/AbdiasSoftware/kqW4X/
The old drawn rectangle vanishes on click because, you are clearing the entire canvas each time before drawing a rectangle.
The easiest workaround would be to save the entire canvas as an image on mouseup and draw that image before drawing each rectangle.
var canvas;
var _foo = new foo();
canvas.onmousedown = _foo.mousedown;
canvas.onmousemove= _foo.mousemove;
canvas.onmouseup = _foo.mouseup;
function foo() {
canvas = $('#canvas')[0];
var context = canvas.getContext('2d');
var checkboxSquare = $('#checkboxSquare')[0];
var img = new Image();
var tool = this;
this.started = false;
var last_mousex = 0;
var last_mousey = 0;
var mousex = 0;
var mousey = 0;
this.mousedown = function (ev) {
if(checkboxSquare.checked) {
last_mousex = ev.offsetX;
last_mousey = ev.offsetY;
context.strokeStyle = $('#selectColor').val();
context.lineWidth = $('#selectWidth').val();
tool.started = true;
}
};
this.mousemove = function (ev) {
if (tool.started && checkboxSquare.checked) {
mousex = ev.offsetX;
mousey = ev.offsetY;
context.clearRect(0, 0, canvas.width, canvas.height); // clear canvas
context.drawImage(img, 0, 0); // draw saved canvas (image)
context.beginPath();
var width = mousex-last_mousex;
var height = mousey-last_mousey;
context.rect(last_mousex,last_mousey,width,height);
context.stroke();
}
};
this.mouseup = function (ev) {
if (tool.started && checkboxSquare.checked) {
tool.mousemove(ev);
img.src = canvas.toDataURL(); // save canvas as image
tool.started = false;
}
};
}
canvas {
border: 1px solid black;
cursor: default;
margin-top: 5px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="checkboxSquare">Square | Color
<select id="selectColor">
<option value="red">red</option>
<option value="green">green</option>
<option value="blue">blue</option>
</select> | Width
<select id="selectWidth">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<canvas id="canvas" width="400" height="400"></canvas>
Just create a background canvas same as the main canvas. When you drag out a new box, first draw the background canvas (with all the past boxes) on the main canvas then the current box being drawn. When you finish dragging the box, just daw it to the background canvas.
const canvas = document.createElement("canvas");
const background = document.createElement("canvas");
canvas.style.border="2px solid black";
canvas.style.cursor = "crosshair";
background.width = canvas.width = innerWidth - 24;
background.height = canvas.height = innerHeight - 24;
const ctx = canvas.getContext("2d");
background.ctx = background.getContext("2d");
document.body.appendChild(canvas);
const bounds = canvas.getBoundingClientRect();
var currentBox;
const boxStyle = {
fillStyle : "#4aF",
strokeStyle : "black",
lineWidth : 3,
lineJoin : "round",
}
const mouse = { x : 0, y : 0,button : false, changed : false };
["mousemove","mousedown","mouseup"].forEach(en => document.addEventListener(en, mouseEvent));
function createBox(x,y,w,h,style){ return {x,y,w,h,style,draw : drawBox} }
function drawBox(ctx){
setStyle(ctx, this.style);
ctx.beginPath();
ctx.rect(this.x,this.y,this.w,this.h);
ctx.fill();
ctx.stroke();
}
function setStyle(ctx, style){ Object.keys(style).forEach(key => ctx[key] = style[key]) }
function mouseEvent(event) {
mouse.x = event.pageX - bounds.left - scrollX;
mouse.y = event.pageY - bounds.top - scrollY;
if(event.type === "mousedown"){ mouse.button = true }
else if(event.type === "mouseup"){ mouse.button = false }
mouse.changed = true;
}
function mainLoop(){
var b = currentBox; // alias for readability
if(mouse.changed){
if(mouse.button){
if(!b){
b = currentBox = createBox(mouse.x,mouse.y,0,0,boxStyle);
}else{
b.w = mouse.x - b.x;
b.h = mouse.y - b.y;
}
}else if(b){
b.draw(background.ctx);
b = currentBox = undefined;
}
if(b){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(background,0,0);
b.draw(ctx);
canvas.style.cursor = "none";
}else{
canvas.style.cursor = "crosshair";
}
mouse.changed = false;
}
requestAnimationFrame(mainLoop);
}
requestAnimationFrame(mainLoop);
Extra Note. Capture the mouse using the Document
When you create canvas drawing apps you should listen to the document mouse events rather than the canvas. When the mouse button is down the mouse is captured and will continue to send mouse events while the mouse is down, even if you have moved off the canvas, document, or event outside the browser window.
This means you can drag content of the canvas and not worry about losing the mouseup event.
Burn some time.
I have some time to burn so will extend the demo above to include selecting and moving existing boxes. Draw boxes as normal. Mouse over boxes will highlight them, click to select them. When selected can be dragged. Uses the same method background image to hold old boxes. But have added a box list to hold old boxes
A more extensive example
const canvas = document.createElement("canvas");
const background = document.createElement("canvas");
canvas.style.border="2px solid black";
canvas.style.cursor = "crosshair";
background.width = canvas.width = innerWidth - 24;
background.height = canvas.height = innerHeight - 24;
const ctx = canvas.getContext("2d");
background.ctx = background.getContext("2d");
document.body.appendChild(canvas);
const bounds = canvas.getBoundingClientRect();
var currentBox;
var selectedBox;
var mouseOverBox;
const styles = {
box : {
fillStyle : "#4aF",
strokeStyle : "black",
lineWidth : 3,
lineJoin : "round",
},
highlight : {
strokeStyle : "white",
lineWidth : 1,
lineJoin : "round",
setLineDash : [[10,10]],
},
selected : {
strokeStyle : "red",
lineWidth : 2,
lineJoin : "round",
setLineDash : [[5,5]],
},
}
const boxes = {
items : [],
add(box){ // add a box and fix width and height to positive
if(box.w < 0){
box.x += box.w;
box.w = -box.w;
}
if(box.h < 0){
box.y += box.h;
box.h = -box.h;
}
boxes.items.push(box)
},
apply(name, ...args){
for(var i = 0; i < boxes.items.length; i ++ ){
boxes.items[i][name](...args);
}
},
};
const mouse = { x : 0, y : 0,button : false, changed : false };
["mousemove","mousedown","mouseup"].forEach(en => document.addEventListener(en, mouseEvent));
const boxBehaviours = {
draw(ctx, style = this.style){
if(!this.hide){
setStyle(ctx, style);
ctx.beginPath();
ctx.rect(this.x,this.y,this.w,this.h);
if(style.fillStyle) { ctx.fill() }
if(style.strokeStyle) {ctx.stroke() }
}
},
isPointOver(x,y){
var b = this;
if(x >= b.x && x < b.x + b.w && y >= b.y && y < b.y + b.h){
b.mouseOver = true;
boxBehaviours.topMouseBox = b;
}else {
b.mouseOver =false;
}
},
}
function createBox(x,y,w,h,style){
return {x,y,w,h,style, ...boxBehaviours};
}
function setStyle(ctx, style){
Object.keys(style).forEach(key => {
if(typeof ctx[key] === "function"){
ctx[key](...style[key]);
}else{
ctx[key] = style[key];
}
})
}
function mouseEvent(event) {
mouse.x = event.pageX - bounds.left - scrollX;
mouse.y = event.pageY - bounds.top - scrollY;
if(event.type === "mousedown"){ mouse.button = true }
else if(event.type === "mouseup"){ mouse.button = false }
}
function redrawBackground(){
background.ctx.clearRect(0,0,canvas.width,canvas.height)
boxes.apply("draw",background.ctx);
}
function mainLoop(time){
var b = currentBox; // alias for readability
var mob = mouseOverBox; // alias for readability
var sb = selectedBox; // alias for readability
// first check mouse button. If button down could be
// dragging a selected box or creating a new box
if(mouse.button){
if(sb){ // is selected box
if(!mouse.drag){ // start the drag
mouse.drag = {x : mouse.x - sb.x, y : mouse.y - sb.y}
}else{ // move the box
sb.x = mouse.x- mouse.drag.x;
sb.y = mouse.y- mouse.drag.y;
}
}else{ // else muse be create (or select click)
if(!b){
b = currentBox = createBox(mouse.x,mouse.y,0,0,styles.box);
}else{
b.w = mouse.x - b.x;
b.h = mouse.y - b.y;
}
}
}else if(b || sb){ // mouse up and there is a box
if(sb){ // if selected box
if(mouse.drag){ // is dragging then drop it
mouse.drag = undefined;
sb.hide = false;
redrawBackground();
sb = selectedBox = undefined;
}
// is the mouse is down and has not moved over 2 pixels
// and there is a mob (mouseOverBox) under it
// then dump the new box and select the mob box
}else if(Math.abs(b.w) < 2 && Math.abs(b.h) < 2 && mob){
sb = selectedBox = mob;
mob = mouseOverBox = undefined;
b = currentBox = undefined;
sb.hide = true;
redrawBackground();
}else{
// just a normal box add it to box array
// draw it and remove it from currentBox
boxes.add(b);
b.draw(background.ctx);
b = currentBox = undefined;
}
}
// clear andf draw background
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(background,0,0);
if(b){ // is there a current box then draw that
b.draw(ctx);
canvas.style.cursor = "none";
} else { // no current box so
// find any boxes under the mouse
boxBehaviours.topMouseBox = null;
boxes.apply("isPointOver",mouse.x, mouse.y);
// is there a selected box (sb)
if(sb){ // yes selected box then draw it
ctx.save();
styles.selected.lineDashOffset = time / 25;
sb.hide = false;
sb.draw(ctx,styles.selected);
sb.hide = true;
ctx.restore();
canvas.style.cursor = "move";
// no selected box sp then just high light the box under the
// mouse and assign it to mouseOverBox (mob);
}else if(boxBehaviours.topMouseBox){
mob = mouseOverBox = boxBehaviours.topMouseBox;
ctx.save();
styles.highlight.lineDashOffset = time / 20;
mob.draw(ctx, styles.highlight);
ctx.restore();
canvas.style.cursor = "pointer";
}else{
canvas.style.cursor = "crosshair";
}
}
requestAnimationFrame(mainLoop);
}
requestAnimationFrame(mainLoop);
var point = [];
var clicks = 0;
var sketch = document.querySelector('#sketch');
var sketch_style = getComputedStyle(sketch);
// Creating a tmp canvas
var tmp_canvas = document.createElement('canvas');
var tmp_ctx = tmp_canvas.getContext('2d');
tmp_canvas.id = 'tmp_canvas';
tmp_canvas.width = parseInt(sketch_style.getPropertyValue('width'));
tmp_canvas.height = parseInt(sketch_style.getPropertyValue('height'));
sketch.appendChild(tmp_canvas);
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.id = 'paint';
canvas.width = parseInt(sketch_style.getPropertyValue('width'));
canvas.height = parseInt(sketch_style.getPropertyValue('height'));
sketch.appendChild(canvas);
tmp_canvas.addEventListener('mousedown', mousedown, false);
tmp_canvas.addEventListener('mousemove', mousemove, false);
tmp_canvas.addEventListener('mouseup', mouseup, false);
function mousemove(e) {
if (clicks == 1) {
x = e.layerX - this.offsetLeft;
y = e.layerY - this.offsetTop;
showRect(x, y);
}
}
function showRect(x, y) {
tmp_ctx.clearRect(0, 0, canvas.width, canvas.height); // clear canvas
tmp_ctx.beginPath();
var width = x - point[0].x;
var height = y - point[0].y;
tmp_ctx.rect(point[0].x, point[0].y, width, height);
tmp_ctx.stroke();
}
function mousedown(e) {
x = e.layerX - this.offsetLeft;
y = e.layerY - this.offsetTop;
point.push({
x,
y
});
clicks++;
};
function mouseup() {
context.drawImage(tmp_canvas, 0, 0);
clicks = 0;
point.length = 0;
}
html, body {
width: 100% ;
height: 100% ;
}
#sketch {
border: 10px solid gray;
height: 100% ;
position: relative;
}
#tmp_canvas {
position: absolute;
left: 0px;
right: 0;
bottom: 0;
top: 0;
cursor: crosshair;
}
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="sketch">
</div>
</body>
</html>
Try to do in temporary canvas and redraw all in main.
jsfiddle:-https://jsfiddle.net/durga598/v0m06faz/
I'm assuming that the foo() function is being called for every frame, either through setInterval or requestAnimationFrame. If my assumption is right, the reason why your previously drawn square disappears is because you are only storing the x and y coordinates of one rectangle, and every time you click on the canvas again, it gets overwritten by the new values for the new rectangle.
To solve your problem, you should store the x and y coordinates as well as the dimensions of the square on mouseup. These coordinates can be stored in an array.
var squares = [];
this.mouseup = function (ev) {
// other code
var square = {
x: last_mousex,
y: last_mousey,
width: mousex - last_mousex,
height: mousey - last_mousey
};
squares.push(square);
};
Now every time you draw the square, draw the squares stored in the squares array first.
this.mousemove = function (ev) {
if (tool.started && checkboxSquare.checked) {
// other code
context.clearRect(0, 0, canvas.width, canvas.height); // clear canvas
// draw each square in the squares array after clearning the canvas
squares.forEach(function(square) {
context.beginPath();
context.rect(square.x, square.y, square.width, square.height);
});
context.beginPath();
var width = mousex - last_mousex;
var height = mousey - last_mousey;
context.rect(last_mousex, last_mousey, width, height);
context.stroke();
}
};
You'll see some code repetitions in drawing the squares, it's a good opportunity to abstract it into a separate function.

Why is my code working on jsfiddle but not my HTML file

I am using jsfiddle to store some coordinates. The coordinates gets displayed on jsfiddle but when I copy it on my local files the coordinates don't get displayed.
I would like to display the coordinates of that line on my local files, How can this be done?
This is my HTML file
<canvas id="canvas" width="300" height="300" style="border: 1px solid black;"> </canvas>
<div id="coord"></div>
<div id="coords"></div>
This is my Javascript File
var canvas = document.getElementById('canvas'),
coord = document.getElementById('coord'),
ctx = canvas.getContext('2d'), // get 2D context
imgCat = new Image(),
arr = [];
imgCat.src = ''http://c.wearehugh.com/dih5/openclipart.org_media_files_johnny_automatic_1360.png';
imgCat.onload = function() { // wait for image load
ctx.drawImage(imgCat, 0, 0); // draw imgCat on (0, 0)
};
var mousedown = false;
ctx.strokeStyle = '#0000FF';
ctx.lineWidth = 5;
canvas.onmousedown = function(e) {
arr = [];
var pos = fixPosition(e, canvas);
mousedown = true;
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
return false;
};
canvas.onmousemove = function(e) {
var pos = fixPosition(e, canvas);
coord.innerHTML = '(' + pos.x + ',' + pos.y + ')';
if (mousedown) {
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
arr.push([pos.x, pos.y])
}
};
canvas.onmouseup = function(e) {
mousedown = false;
$('#coords').html(JSON.stringify(arr, null, 2));
};
function fixPosition(e, gCanvasElement) {
var x;
var y;
if (e.pageX || e.pageY) {
x = e.pageX;
y = e.pageY;
}
else {
x = e.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}
x -= gCanvasElement.offsetLeft;
y -= gCanvasElement.offsetTop;
return {x: x, y:y};
}
Demo Here
Copy this in a html page. The probleme was your link imgCat.src = ''http://c.wearehugh.com/dih5/openclipart.org_media_files_johnny_automatic_1360.png';
You put two ''
<html>
<canvas id="canvas" width="300" height="300" style="border: 1px solid black;"></canvas>
<div id="coord"></div>
<div id="coords"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js</script>
</html>
<script type="text/javascript">
var canvas = document.getElementById('canvas'),
coord = document.getElementById('coord'),
ctx = canvas.getContext('2d'), // get 2D context
imgCat = new Image(),
arr = [];
imgCat.src ='http://www.clipartbest.com/cliparts/bTy/E5x/bTyE5xLjc.png';
imgCat.onload = function() { // wait for image load
ctx.drawImage(imgCat, 0, 0); // draw imgCat on (0, 0)
};
var mousedown = false;
ctx.strokeStyle = '#0000FF';
ctx.lineWidth = 5;
canvas.onmousedown = function(e) {
arr = [];
var pos = fixPosition(e, canvas);
mousedown = true;
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
return false;
};
canvas.onmousemove = function(e) {
var pos = fixPosition(e, canvas);
coord.innerHTML = '(' + pos.x + ',' + pos.y + ')';
if (mousedown) {
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
arr.push([pos.x, pos.y])
}
};
canvas.onmouseup = function(e) {
mousedown = false;
$('#coords').html(JSON.stringify(arr, null, 2));
};
function fixPosition(e, gCanvasElement) {
var x;
var y;
if (e.pageX || e.pageY) {
x = e.pageX;
y = e.pageY;
}
else {
x = e.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}
x -= gCanvasElement.offsetLeft;
y -= gCanvasElement.offsetTop;
return {x: x, y:y};
}
</script>
some configuration is applying to jsfiddle automatically and you need to apply them by your hands.
first you need to add jQuery to you site. Add this line between <head> </head> tags:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
second you need to check that you script executes for example when page loads. you need to put you code into this:
$(function() {
// You script here
});
or put it just before </body> tag
so in output you jquery code will be like this:
<script>
$(function() {
var canvas = document.getElementById('canvas'),
coord = document.getElementById('coord'),
ctx = canvas.getContext('2d'), // get 2D context
imgCat = new Image(),
arr = [];
imgCat.src = ''http://c.wearehugh.com/dih5/openclipart.org_media_files_johnny_automatic_1360.png';
imgCat.onload = function() { // wait for image load
ctx.drawImage(imgCat, 0, 0); // draw imgCat on (0, 0)
};
var mousedown = false;
ctx.strokeStyle = '#0000FF';
ctx.lineWidth = 5;
canvas.onmousedown = function(e) {
arr = [];
var pos = fixPosition(e, canvas);
mousedown = true;
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
return false;
};
canvas.onmousemove = function(e) {
var pos = fixPosition(e, canvas);
coord.innerHTML = '(' + pos.x + ',' + pos.y + ')';
if (mousedown) {
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
arr.push([pos.x, pos.y])
}
};
canvas.onmouseup = function(e) {
mousedown = false;
$('#coords').html(JSON.stringify(arr, null, 2));
};
function fixPosition(e, gCanvasElement) {
var x;
var y;
if (e.pageX || e.pageY) {
x = e.pageX;
y = e.pageY;
}
else {
x = e.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}
x -= gCanvasElement.offsetLeft;
y -= gCanvasElement.offsetTop;
return {x: x, y:y};
}
});
</script>
1.Check the doc type of the HTML :should be html for (HTML 5)or no doc type
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2.Make sure your scripts are getting loaded properly.
Check the path of Jquery script.
--Externally downloaded scripts need to be unblocked
(Righ Click -> Properties -> (General Tab)'Unblock' Option on bottom)
(Right Click -> Properties -> (general Tab) -> Advanced -> Uncheck Encrypt option if checked.)
3.Put your code inside a function.
(Specifically the binding related codes.)
Other functions need to be defined outside document ready.(Already done)
And Call that function inside document ready.
$(document).ready(function () {
DrawImage();
});
function DrawImage()
{
//your code here
var canvas = document.getElementById('canvas'),
coord = document.getElementById('coord'),
ctx = canvas.getContext('2d'), // get 2D context
imgCat = new Image(),
arr = [];
/*********** draw image *************/
imgCat.src = 'http://c.wearehugh.com/dih5/openclipart.org_media_files_johnny_automatic_1360.png';
imgCat.onload = function() { // wait for image load
ctx.drawImage(imgCat, 0, 0); // draw imgCat on (0, 0)
};
/*********** handle mouse events on canvas **************/
var mousedown = false;
ctx.strokeStyle = '#0000FF';
ctx.lineWidth = 5;
canvas.onmousedown = function(e) {
arr = [];
var pos = fixPosition(e, canvas);
mousedown = true;
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
return false;
};
canvas.onmousemove = function(e) {
var pos = fixPosition(e, canvas);
coord.innerHTML = '(' + pos.x + ',' + pos.y + ')';
if (mousedown) {
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
arr.push([pos.x, pos.y])
}
};
canvas.onmouseup = function(e) {
mousedown = false;
$('#coords').html(JSON.stringify(arr, null, 2));
};
}
//Utils
function fixPosition(e, gCanvasElement) {
//put codes of this function here.
}
just add your script before end of body tag and your problem will solve.

Categories