Scrolling issue with Canvas style.left/top - javascript

I am making a magnifying glass for a canvas application but ive run into an issue with scrolling.
Essentially the goal is to take a canvas and when an image is added (in this case a cgm image) and make a snapshot of it, scale it up and draw it on to a second smaller canvas that overlays it and follow the mouse (preferably a drag/mousedown and up, but i am using mousemove for testing purposes). I believe the issue is in the zoom.style.top & zoom.style.left NOTE on my main aplication I have a top margin of 70px so keep that in mind.
here is a quick example I wrote up
<!-- language: lang-js -->
var canvas = document.getElementById("canvas1");
var ctx = canvas.getContext("2d");
var ox = canvas.width / 2;
var oy = canvas.height / 2;
ctx.font = "42px serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "blue";
ctx.fillRect(ox / 2, oy / 2, ox, oy);
function magnify() {
var main = document.getElementById("canvas1");
var ctx = main.getContext('2d')
var base64 = main.toDataURL('image/png', 0);
drawing = new Image();
drawing.onload = () => {
var zoom = document.getElementById("tCanvas");
var zoomCtx = zoom.getContext('2d');
zoomCtx.drawImage(drawing, 0, 0);
}
main.addEventListener("mousemove", function(e) {
var zoom = document.getElementById("tCanvas");
var zoomCtx = zoom.getContext('2d');
zoomCtx.clearRect(0, 0, zoom.width, zoom.height);
zoomCtx.drawImage(main, e.x, e.y, 200, 200, 0, 0, 300, 300);
zoom.style.top = e.pageY - 70 + "px"
zoom.style.left = e.pageX - 10 + "px"
e.pageY = -150
e.pageX = -150
zoom.style.display = "block";
});
main.addEventListener("mouseleave", function() {
var zoom = document.getElementById("tCanvas");
zoom.style.display = "none";
});
drawing.src = base64;
};
<canvas id="tCanvas" class="cgm" height="100" width="100" style="background-color:white; position: absolute; display: none; z-
index:1;border:1px solid red;"> </canvas>
<canvas tabindex=1 class="cgm" id="canvas1" style="position:relative; background:white;
left:0;right:0;margin:auto;z-index:1;margin-top:70px; "></canvas>
<p></p>
<button id="zoom" onclick="magnify();">Zoom</button>
Here's a fiddle for reference (I fixed the height to display the scroll issue).
JSFiddle

I simplified a lot of the code on your JSFiddle.
See if this is the behavior you are looking for:
const canvas = document.getElementById("canvas1");
const ctx = canvas.getContext("2d");
const zoom = document.getElementById("tCanvas");
const zoomCtx = zoom.getContext('2d');
for (let i = 10; i < 20; i++)
for (let j = -60; j < 800; j += 60)
ctx.fillText(j + i, i * 20 - 180, i * 9 + j);
function getMousePos(evt) {
var rect = canvas.getBoundingClientRect()
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
}
}
canvas.addEventListener("mousemove", function(e) {
zoomCtx.clearRect(0, 0, zoom.width, zoom.height);
let pos = getMousePos(e)
zoomCtx.drawImage(canvas, pos.x, pos.y, 200, 200, 0, 0, 300, 300);
zoom.style.top = e.pageY - 10 + "px"
zoom.style.left = e.pageX - 10 + "px"
zoom.style.display = "block";
});
canvas.addEventListener("mouseleave", function() {
zoom.style.display = "none";
});
#tCanvas {
border: 1px solid red;
display: none;
position: absolute;
background-color: #808080;
pointer-events: none;
}
#canvas1 {
background-color: #808080;
}
<canvas id="tCanvas" width=100 height=100></canvas>
<canvas id="canvas1" width=240 height=800></canvas>
I think that your issue was with pointer-events: none; the top canvas was preventing the events from reaching the bottom canvas.
Also you don't have to declare your document.getElementById(".. on every function, those should be global constants
For the issue with a long canvas we need to use canvas.getBoundingClientRect in the calculation to get the real position of the mouse in the canvas

Related

Need help writing a function to make any box inside the grid clickable and filled with colorwheel

I'm working on a pixel art project. What I was expecting to do here is be able to click any box inside the grid and render it with the the color from a color input.
I managed to understand how the loop works to create a grid using canvas and javascript. Next, I created a function called colorPicker() which allows me to click on any of the grid cells and take the value from the color input and render it that color. I used canvas.addEventListener("click", function(event) { ... })
and passed variables xCoord and yCoord with the value of event.x and event.y. This allows me to return the position of the mouse on click inside the grid.
The problem I'm running into right now is that it is only rendering 1 square out of all 400 I have drawn on the grid. The rendering works, it's just I can only click one box and render its color from the input.
Can anyone provide me with some help to solve this function just using the javascript logic I currently have right now?
var title = document.getElementById("title");
var canvas = document.getElementById("canvas");
var color = document.getElementById("color");
var btn = document.getElementById("btn");
var ctx = canvas.getContext("2d");
// The function that draws the grid
function drawGrid() {
ctx.fillStyle = "#009EFF";
ctx.fillRect(0, 0, 400, 400);
ctx.strokeStyle = "black";
ctx.lineWidth = 1;
// The for loop that draws the x-axis
for (x = 0; x <= 400; x += 20) {
ctx.moveTo(x, 0);
ctx.lineTo(x, 400);
ctx.stroke();
}
// The for loop that draws the y-axis
for (y = 0; y <= 400; y += 20) {
ctx.moveTo(0, y);
ctx.lineTo(400, y);
ctx.stroke();
}
}
drawGrid();
// Function that clicks and fill grid boxes w / color
function colorPicker() {
canvas.addEventListener("click", function(event) {
var newColor = color.value;
ctx.fillStyle = newColor;
xCoord = event.x;
yCoord = event.y;
ctx.fillRect(0, 0, 20, 20);
console.log(xCoord, yCoord);
console.log(newColor);
});
}
colorPicker();
#canvas {
border: 1px solid black;
background-size: 100%;
display: block;
margin-top: 50px;
margin-left: auto;
margin-right: auto;
padding-left: 0;
padding-right: 0;
}
<div class="color-wheel">
Color: <input type="color" id="color" />
</div>
<canvas id="canvas" width="400" height="400"></canvas>
Your problem is this line:
ctx.fillRect(0, 0, 20, 20);
Instead of filling the clicked cell, you’re filling only the upper left cell on every click.
Currently you’re just using (0, 0) here, when you should be calculating this position from the cursor. The coordinates used by the canvas and the cursor are different though, so you’ll need to write a conversion function:
function mousePosToCanvasPos(mouseX, mouseY) {
var canvasPos = canvas.getBoundingClientRect();
return {
x: Math.floor((mouseX - canvasPos.x) / 20) * 20,
y: Math.floor((mouseY - canvasPos.y) / 20) * 20,
};
}
The mousePosToCanvasPos() function gets the current rendered position of the canvas (canvasPos), and calculates the offset of the cursor from the upper left corner of the canvas (mouse_ - canvasPos._). It then rounds this value down to the nearest multiple of 20 to return the upper left corner of the clicked cell (Math.floor((mouse_ - canvasPos._) / 20) * 20). If you change your cell size to something other than 20, be sure to change it in this function too. Or better yet, extract the constant (var cellSize = 20).
Adding this function to your code gives us:
var title = document.getElementById("title");
var canvas = document.getElementById("canvas");
var color = document.getElementById("color");
var btn = document.getElementById("btn");
var ctx = canvas.getContext("2d");
// The function that draws the grid
function drawGrid() {
ctx.fillStyle = "#009EFF";
ctx.fillRect(0, 0, 400, 400);
ctx.strokeStyle = "black";
ctx.lineWidth = 1;
// The for loop that draws the x-axis
for (x = 0; x <= 400; x += 20) {
ctx.moveTo(x, 0);
ctx.lineTo(x, 400);
ctx.stroke();
}
// The for loop that draws the y-axis
for (y = 0; y <= 400; y += 20) {
ctx.moveTo(0, y);
ctx.lineTo(400, y);
ctx.stroke();
}
}
drawGrid();
function mousePosToCanvasPos(mouseX, mouseY) {
var canvasPos = canvas.getBoundingClientRect();
return {
x: Math.floor((mouseX - canvasPos.x) / 20) * 20,
y: Math.floor((mouseY - canvasPos.y) / 20) * 20,
};
}
// Function that clicks and fill grid boxes w / color
function colorPicker() {
canvas.addEventListener("click", function(event) {
var newColor = color.value;
ctx.fillStyle = newColor;
var canvasCellPos = mousePosToCanvasPos(event.x, event.y);
ctx.fillRect(canvasCellPos.x, canvasCellPos.y, 20, 20);
console.log(event.x, event.y);
console.log(newColor);
});
}
colorPicker();
#canvas {
border: 1px solid black;
background-size: 100%;
display: block;
margin-top: 50px;
margin-left: auto;
margin-right: auto;
padding-left: 0;
padding-right: 0;
}
<div class="color-wheel">
Color: <input type="color" id="color" />
</div>
<canvas id="canvas" width="400" height="400"></canvas>
You’ll notice that something’s still not quite right here: every time you fill a cell, it makes its border thinner. To solve this, you need to remove one pixel from each side of your fillRect:
ctx.fillRect(canvasCellPos.x + 1, canvasCellPos.y + 1, 18, 18);
var title = document.getElementById("title");
var canvas = document.getElementById("canvas");
var color = document.getElementById("color");
var btn = document.getElementById("btn");
var ctx = canvas.getContext("2d");
// The function that draws the grid
function drawGrid() {
ctx.fillStyle = "#009EFF";
ctx.fillRect(0, 0, 400, 400);
ctx.strokeStyle = "black";
ctx.lineWidth = 1;
// The for loop that draws the x-axis
for (x = 0; x <= 400; x += 20) {
ctx.moveTo(x, 0);
ctx.lineTo(x, 400);
ctx.stroke();
}
// The for loop that draws the y-axis
for (y = 0; y <= 400; y += 20) {
ctx.moveTo(0, y);
ctx.lineTo(400, y);
ctx.stroke();
}
}
drawGrid();
function mousePosToCanvasPos(mouseX, mouseY) {
var canvasPos = canvas.getBoundingClientRect();
return {
x: Math.floor((mouseX - canvasPos.x) / 20) * 20,
y: Math.floor((mouseY - canvasPos.y) / 20) * 20,
};
}
// Function that clicks and fill grid boxes w / color
function colorPicker() {
canvas.addEventListener("click", function(event) {
var newColor = color.value;
ctx.fillStyle = newColor;
var canvasCellPos = mousePosToCanvasPos(event.x, event.y);
ctx.fillRect(canvasCellPos.x + 1, canvasCellPos.y + 1, 18, 18);
console.log(event.x, event.y);
console.log(newColor);
});
}
colorPicker();
#canvas {
border: 1px solid black;
background-size: 100%;
display: block;
margin-top: 50px;
margin-left: auto;
margin-right: auto;
padding-left: 0;
padding-right: 0;
}
<div class="color-wheel">
Color: <input type="color" id="color" />
</div>
<canvas id="canvas" width="400" height="400"></canvas>

HTML5 canvas stroke with consistent alpha values

I am developing a image masking tool that helps the user mark a certain regions on an underlying image. I'd like the mask to have a consistent alpha-value. The masking tool is to be implemented in HTML5 canvas.
The issue I'm facing is that when I create multiple over-lapping strokes, their alpha values stack, making it less-transparent in the overlaps. Whereas I'd like a consistent alpha value regardless of overlapping strokes, as the user might need multiple strokes to fully mask a region.
Here is the attached fiddle:
http://jsfiddle.net/o5x70fbd/
Let me know if this is a known solution
I don't know if this is the solution you are looking for. My idea is to use 2 canvases. In the first canvas the color of the stroke is opaque. This canvas is hidden. I'm using display:nonebut you can let it unattached to the DOM.
Then you copy the first canvas as an image in a second one with ctx2.globalAlpha = .5;. this will give you a a consistent alpha value.
The changes I've made to your code: I'm putting the points in arrays and I'm drawing using the points:
var canvas = document.getElementById("myCanvas");
var canvas2 = document.getElementById("_2");
var ctx = canvas.getContext("2d");
var ctx2 = _2.getContext("2d");
var drawing = false;
let points = [];
var painting = document.getElementById("paint");
var paint_style = getComputedStyle(painting);
canvas.width = canvas2.width = parseInt(paint_style.getPropertyValue("width"));
canvas.height = canvas2.height = parseInt(
paint_style.getPropertyValue("height")
);
var mouse = {
x: 0,
y: 0
};
let count = -1;
ctx.lineWidth = 30;
ctx.lineJoin = "round";
ctx.lineCap = "round";
_2.addEventListener(
"mousemove",
function(e) {
if (drawing) {
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
points[count].push({ x: mouse.x, y: mouse.y });
onPaint();
}
},
false
);
_2.addEventListener(
"mousedown",
function(e) {
drawing = true;
count++;
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
let ry = [];
ry.push({ x: mouse.x, y: mouse.y });
points.push(ry);
},
false
);
_2.addEventListener(
"mouseup",
function() {
drawing = false;
onPaint();
},
false
);
function onPaint() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
points.forEach(ry => {
ctx.beginPath();
ctx.moveTo(ry[0].x, ry[0].y);
ry.forEach(p => {
ctx.lineTo(p.x, p.y);
});
ctx.strokeStyle = "#00CC99";
ctx.stroke();
});
ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
ctx2.globalAlpha = 0.5;
ctx2.drawImage(canvas, 0, 0);
}
body {
margin: 0px;
padding: 0px;
}
#paint {
width: 98%;
height: 550px;
border: 5px solid red;
}
#myCanvas{display:none;}
#_2{background:url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/castell.jpg)}
<div id="paint">
<canvas id="myCanvas"></canvas>
<canvas id="_2"></canvas>
</div>

canvas drawing margin correction

I'm trying some draw techniques I found in this URL:
http://perfectionkills.com/exploring-canvas-drawing-techniques/
I just noticed that the higher level css properties are not applied to the canvas element mouse events. Is there a easy way to fix this?
<head>
<meta charset="utf-8">
<title>Spray Can</title>
<style>
body {
margin: 0;
padding: 0;
}
#container {
border: 1px solid #ccc;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#canvas {
}
</style>
<script>
document.addEventListener('DOMContentLoaded', function () {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var isDrawing;
canvas.onmousedown = function(e) {
isDrawing = true;
context.moveTo(e.clientX, e.clientY);
};
canvas.onmousemove = function(e) {
if (isDrawing) {
var k = 4;
var radgrad = context.createRadialGradient(e.clientX, e.clientY, k, e.clientX, e.clientY, k * 2);
radgrad.addColorStop(0, 'rgba(0,0,0,1)');
radgrad.addColorStop(0.5, 'rgba(0,0,0,0.5)');
radgrad.addColorStop(1, 'rgba(0,0,0,0)');
context.fillStyle = radgrad;
context.fillRect(e.clientX - k * 2, e.clientY - k * 2, k * 2 * 2, k * 2 * 2);
}
};
canvas.onmouseup = function() {
isDrawing = false;
};
});
</script>
</head>
<body>
<div id="container">
<canvas id="canvas" width="400" height="400"></canvas>
</div>
</body>
https://jsfiddle.net/crpq8t5q/1/
What you need is to convert your mouse event's coordinates to be relative to the canvas ones.
Since here you don't touch the scale nor rotation this is just a simple canvasX = mouseX - canvas.offsetLeft and canvasY = mouseY - canvas.offsetTop.
These offsetXXX properties are available on the canvas, but you can also use getBoundingClientRect()which will return better results if your css is more complicated (e.g nested elements with different scrollable areas).
But since this offset will change each time you scroll or resize the page, you need to update these values.
Also, it is a very bad idea to create a readialGradient in a mouse event. This event can fire at really high rate, and creating gradients eats memory.
It is then better to create a single gradient, and modify your whole context's matrix so that the gradient be placed at the mouse coordinates :
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var isDrawing;
var k = 4;
// create the gradient only once
var radgrad = context.createRadialGradient(0, 0, k, 0, 0, k * 2);
radgrad.addColorStop(0, 'rgba(0,0,0,1)');
radgrad.addColorStop(0.5, 'rgba(0,0,0,0.5)');
radgrad.addColorStop(1, 'rgba(0,0,0,0)');
// get our canvas margins;
var rect;
function getRect() {
rect = canvas.getBoundingClientRect();
}
canvas.onmousedown = function(e) {
isDrawing = true;
context.moveTo(e.clientX, e.clientY);
};
canvas.onmousemove = function(e) {
if (isDrawing) {
// normalize our mouse event's coordinates
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
// change the canvas matrix coordinates so we draw at mouse positions
context.setTransform(1, 0, 0, 1, x, y)
context.fillStyle = radgrad;
context.fillRect(-k * 2, -k * 2, k * 2 * 2, k * 2 * 2);
}
};
canvas.onmouseup = function() {
isDrawing = false;
};
var debouncing = false;
function resizeHandler() {
debouncing = false;
getRect();
}
window.onscroll = window.onresize = function() {
// debounce the events
if (!debouncing) {
requestAnimationFrame(resizeHandler);
}
debouncing = true;
}
getRect();
body {
margin: 0;
padding: 0;
}
#container {
border: 1px solid #ccc;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#canvas {}
<div id="container">
<canvas id="canvas" width="400" height="400"></canvas>
</div>

How can I make multiple overlaying canvases go fullscreen together and stay overlayed?

I want to make all overlapped HTML5 canvases full-screen when a button is clicked and I want them to stay overlapped when in full-screen mode.
For example I have 3 overlapped canvases. This example came from this site:
HTML
<section>
<div id="canvasesdiv" style="position:relative;width:400px;height:300px">
<canvas id="layer1" style="z-index: 1;position:absolute;left:0px;top:0px;" height="300px" width="400">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
<canvas id="layer2" style="z-index: 2;position:absolute;left:0px;top:0px;" height="300px" width="400">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
<canvas id="layer3" style="z-index: 3;position:absolute;left:0px;top:0px;" height="300px" width="400">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
</div>
<div>
<p>
<button onclick="goFullScreen();">Go Fullscreen</button>
</p>
</div>
...
JavaScript
var layer1;
var layer2;
var layer3;
var ctx1;
var ctx2;
var ctx3;
var x = 400;
var y = 300;
var dx = 2;
var dy = 4;
var WIDTH = 400;
var HEIGHT = 300;
var city = new Image();
function init() {
city.src = "http://html5.litten.com/layers/city.png";
layer1 = document.getElementById("layer1");
ctx1 = layer1.getContext("2d");
layer2 = document.getElementById("layer2");
ctx2 = layer2.getContext("2d");
layer3 = document.getElementById("layer3");
ctx3 = layer3.getContext("2d");
setInterval(drawAll, 20);
}
function drawAll() {
draw1();
draw2();
draw3();
}
function draw1() {
ctx1.clearRect(0, 0, WIDTH, HEIGHT);
ctx1.fillStyle = "#FAF7F8";
ctx1.beginPath();
ctx1.rect(0, 0, WIDTH, HEIGHT);
ctx1.closePath();
ctx1.fill();
ctx1.fillStyle = "#444444";
ctx1.beginPath();
ctx1.arc(x, y, 10, 0, Math.PI * 2, true);
ctx1.closePath();
ctx1.fill();
if (x + dx > WIDTH || x + dx < 0)
dx = -dx;
if (y + dy > HEIGHT || y + dy < 0)
dy = -dy;
x += dx;
y += dy;
}
function draw2() {
ctx2.clearRect(0, 0, WIDTH, HEIGHT);
ctx2.drawImage(city, 0, 0);
}
function draw3() {
ctx3.clearRect(0, 0, WIDTH, HEIGHT);
ctx3.fillStyle = "#444444";
ctx3.save();
ctx3.translate(200, 200);
ctx3.rotate(x / 20);
ctx3.fillRect(-15, -15, 30, 30);
ctx3.restore();
}
function goFullScreen() {
var canvas1 = document.getElementById("layer1");
var canvas2 = document.getElementById("layer2");
var canvas3 = document.getElementById("layer3");
if (canvas1.requestFullScreen){
canvas1.requestFullScreen();
canvas2.webkitRequestFullScreen();
canvas3.webkitRequestFullScreen();
}
else if (canvas1.webkitRequestFullScreen){
canvas1.webkitRequestFullScreen();
canvas2.webkitRequestFullScreen();
canvas3.webkitRequestFullScreen();
}
else if (canvas1.mozRequestFullScreen){
canvas1.mozRequestFullScreen();
canvas2.webkitRequestFullScreen();
canvas3.webkitRequestFullScreen();
}
}
init();
I have tried to implement what discussed in this answer.
I tried to modify the goFullScreen() function is you can see above. But this only make the first canvas full-screen.
Thank your very much for your help.
You will have to request the fullscreen from the parent div and set canvas elements' width to 100% in CSS :
Style :
div:-webkit-full-screen>canvas {
width: 100% !important;
}
div:-moz-full-screen>canvas {
width: 100% !important;
}
div:-ms-fullscreen>canvas {
width: 100% !important;
}
div:fullscreen>canvas {
width: 100% !important;
}
Js :
function goFullScreen() {
var parentDiv = document.getElementById("canvasesdiv");
if (parentDiv.requestFullscreen){
parentDiv.requestFullscreen();}
else if(parentDiv.webkitRequestFullscreen){
parentDiv.webkitRequestFullscreen();
} else if(parentDiv.mozRequestFullScreen){
parentDiv.mozRequestFullScreen();
}
}

Moving a canvas from left to right is not smooth and fast

I want to move one canvas on top of another. when top canvas moves the base canvas displays its x and y. The event initially starts at mouse down. so press mouse and start moving the canvas moves smoothly from right to left but not left to right.
http://jsfiddle.net/happyomi/23PL3/3/
<head>
<style type="text/css">
body, html {
margin: 0;
}
canvas {
position: absolute;
/* top: 0;
left: 0;*/
}
#temp {
background-color: pink;
}
</style>
</head>
<body style="margin: 0; padding: 0; height: 100%; width: 100%; overflow: hidden;">
<canvas id="myCanvas" style="display: block;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<canvas id="temp" style="position: relative">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script type="text/javascript">
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var hgap = 0;
var vgap = 0;
var rows, cols;
var annotation_x = 1;
var row = 0; var col = 0;
//ctx.font = "14px Arial";
c.width = $(document).width();
c.height = $(document).height();
var t = document.getElementById("temp");
tctx = t.getContext("2d");
// tctx.lineWidth = 10;
tctx.lineJoin = 'round';
tctx.lineCap = 'round';
tctx.strokStyle = 'red';
var mouse = { x: 0, y: 0 };
c.addEventListener('mousemove', function (evt) {
mouse.x = evt.pageX;
mouse.y = evt.pageY;
}, false);
c.addEventListener('mousedown', function (evt) {
// tctx.clearRect(0, 0, c.width, c.height);
evt.preventDefault();
ctx.clearRect(0, 0, c.width, c.height);
tctx.clearRect(0, 0, c.width, c.height);
mouse.x = evt.pageX;
mouse.y = evt.pageY;
t.style.left = mouse.x + "px";
t.style.top = mouse.y + "px";
t.style.position = "absolute";
str = "x=" + mouse.x + " y=" + mouse.y;
ctx.fillText(str, 10, 10);
c.addEventListener('mousemove', onPaint, false);
}, false);
var onPaint = function () {
ctx.clearRect(0, 0, c.width, c.height);
tctx.clearRect(0, 0, t.width, t.height);
t.style.left = mouse.x + "px";
t.style.top = mouse.y + "px";
t.style.position = "absolute";
str = "x=" + mouse.x + " y=" + mouse.y;
ctx.fillText(str, 10, 10);
}
c.addEventListener('mouseup', function () {
c.removeEventListener('mousemove', onPaint, false);
}, false);
</script>
</body>
Heres A good Starting point for ya :) it does what your looking for. jsFiddle
/* Main Canvas */
var main = document.getElementById('main');
main.width = window.innerWidth;
main.height = window.innerHeight;
var mainCtx = main.getContext('2d');
var mainFill = '#000';
mainCtx.fillStyle = mainFill;
mainCtx.rect(0,0,main.width,main.height);
mainCtx.fill();
/* secondary canvas */
var cv = document.createElement('canvas');
cv.style.position = 'absolute';
cv.width = '200';
cv.height = '100';
cv.style.left = '0px';
cv.style.top = '0px';
var ctx = cv.getContext('2d');
var fillRect = '#ccc';
var fillText = '#000';
ctx.fillStyle = fillRect;
ctx.rect(0,0,cv.width,cv.height);
ctx.fill();
//draw this canvas to main canvas
mainCtx.drawImage(cv,parseInt(cv.style.left),parseInt(cv.style.top));
var isHolding = false;
var mDown = function(e)
{
isHolding = true;
main.addEventListener('mousemove',mMove);
}
var mMove = function(e)
{
console.log('moving');
if(isHolding)
{
var xPos = e.pageX;
var yPos = e.pageY;
cv.style.left = (xPos-(cv.width/2))+'px';
cv.style.top = (yPos-(cv.height/2))+'px';
cv.width = cv.width; //clears canvas
ctx.fillStyle = fillRect;
ctx.rect(0,0,cv.width,cv.height);
ctx.fill();
ctx.fillStyle = fillText;
ctx.fillText('x: '+e.pageX,10,10);
ctx.fillText('y: '+e.pageY,50,10);
//draw temp canvas to main canvas
this.width = this.width;
mainCtx.fillStyle = mainFill;
mainCtx.rect(0,0,main.width,main.height);
mainCtx.fill();
mainCtx.drawImage(cv,parseInt(cv.style.left),parseInt(cv.style.top));
}
}
var mUp = function(e)
{
isHolding = false;
main.removeEventListener('mousemove',mMove);
}
main.addEventListener('mousedown',mDown);
main.addEventListener('mouseup',mUp);
also it gets rid of the move event when not being used which will help have less event dispatches in memory and help with performance.

Categories

Resources