canvas draw touch is not drawing - javascript

if I enter a position on lineTo() and moveTo() i have a line but if i give the touchstart and touchmove position nothing happens and i have bot console erreur to help me
touchStart(e){
this.touchDessiner(e.changedTouches[0].pageX, e.changedTouches[0].pageY)
console.log(e.changedTouches[0].pageX, e.changedTouches[0].pageY);
}
touchMove(e){
e.preventDefault();
this.touchDessiner(e.changedTouches[0].pageX, e.changedTouches[0].pageY)
console.log(e.changedTouches[0].pageX, e.changedTouches[0].pageY)
}
touchDessiner(x, y){
this.cont.lineWidth = 2;
this.cont.strokeStyle = "#000";
this.cont.beginPath();
this.cont.moveTo(x, y);
this.cont.lineTo(x, y);
this.cont.stroke();
}
thanks for your help

Here is the correct order to draw lines:
On TouchStart:
1. start a new path (lift the pen from the canvas)
2. move the pen here
On TouchMove:
3. with the pen still touching the canvas, move the pen here
canvas = document.getElementById("can");
cont = canvas.getContext("2d");
function touchStart(e){
this.cont.beginPath();
this.cont.moveTo(e.changedTouches[0].pageX, e.changedTouches[0].pageY);
}
function touchMove(e){
e.preventDefault();
this.touchDessiner(e.changedTouches[0].pageX, e.changedTouches[0].pageY)
}
function touchDessiner(x, y){
this.cont.lineWidth = 2;
this.cont.strokeStyle = "#000";
this.cont.lineTo(x, y);
this.cont.stroke();
}
window.addEventListener("touchstart", touchStart);
window.addEventListener("touchmove", touchMove);
<!DOCTYPE html>
<html>
<body>
canvas
<canvas id = "can" style = "border: 1px solid black; position:absolute; left:0px; top:0px;"> </canvas>
</body>
</html>

Related

The Process of Clearing and Redrawing a Square on a HTML Canvas

I have been working on some HTML/Javascript Code and the main thing I want to have happen is when you press any of the arrow keys, the square that I drew moves that direction.
My general train of thought on what I have to do, is when I click on the key, it first clears the canvas, then redraws it with a different x and y value based on the function.
I tried that, but what happens is that the square just vanishes and I have no clue why.
I have been attempting to debug this for a while, and if anyone has any pointers I would love to here them!
<!DOCTYPE html>
<html>
<head>
<title> HTML </title>
<style>
canvas {
border: 1px solid #000000;
}
</style>
</head>
<body>
<center>
<canvas width = "620" height = "620" id = "myCanvas" ></canvas>
</center>
<script src = "script.js" > </script>
</body>
</html>
This is the Javascript Code (Sorry for not well formatting, still getting the hang of formatting code in StackOverflow)
document.addEventListener('keydown', function(event) {
if(event.keyCode == 37)
moveLeft();
if(event.keyCode == 39 )
moveRight();
if(event.keyCode == 38)
moveUp();
if(event.keyCode == 40)
moveDown();
});
function moveLeft() {
context.clearRect(0, 0, canvas.width, canvas.height);
//Edit X and Y Values
var newX, newY;
newX = squareX + 1;
newY = squareY;
context.rect(newX, newY, squareSizeX, squareSizeY);
context.fill(newX, newY, squareSizeX, squareSizeY);
}
function moveRight() {/* Needs to be Finished */}
function moveUp() {/* Needs to be Finished */}
function moveDown() {/* Needs to be Finished */}
var canvas;
var context;
var squareX, squareY;
var squareSizeX = 75;
var squareSizeY = 75;
function renderToCanvas() {
var didRender = false;
try {
canvas = document.getElementById("myCanvas");
context = canvas.getContext("2d");
/* INPUT DRAWING HERE */
//Drawing Square
squareX = canvas.width / 2;
squareY = canvas.height / 2;
context.rect(squareX, squareY, squareSizeX, squareSizeY);
context.fillRect(squareX, squareY, squareSizeX, squareSizeY);
context.stroke();
/* END DRAWING HERE */
didRender = true;
console.log("Rendered Drawing: " + didRender);
}
catch(err) {
console.log("Rendered Drawing: " + didRender);
console.log(err.message);
}
}
renderToCanvas();
In your moveLeft instead of this
context.rect(newX, newY, squareSizeX, squareSizeY);
context.fill(newX, newY, squareSizeX, squareSizeY);
Do this
context.fillRect(newX, newY, squareSizeX, squareSizeY);
Check out the docs for Canvas Context
You only use context.rect() or context.fill() when you are working on a path using context.beginPath()

Javascript paint canvas

I have a problem with my code. It is a simple canvas element drawing circles. There are two things I cannot figure out. The first one is how to draw circles continously (not one at a time) while I keep left mouse button pressed. "Onmousehold" doesn't seem to work here. Secondly is it possible to get rid of the first reference error from the console? It appears only once when coordinates of a click are not yet specified. My code here:
var outer = document.getElementById("outer");
var ctx = outer.getContext("2d");
function getMousePos(e) {
var cursorX = e.clientX;
var cursorY = e.clientY;
x = cursorX;
y = cursorY;
}
function showBox() {
ctx.beginPath();
ctx.arc(x,y,20,0,2*Math.PI);
ctx.stroke();
console.log(x,y);
}
outer.addEventListener("click",getMousePos);
outer.addEventListener("click",showBox);
outer.addEventListener("mousedown",showBox);
#outer {
position:relative;
overflow: hidden;
border: 1px solid green;
}
.popup {
width: 50px;
height: 50px;
border-radius: 25px;
background-color: blue;
position: absolute;
}
<canvas id="outer" width="600" height="600">
</canvas>
And jsfiddle
jsfiddle
see this: http://jsfiddle.net/4ovgzk07/2/
var outer = document.getElementById("outer");
var ctx = outer.getContext("2d");
function getMousePos(e) {
var cursorX = e.clientX;
var cursorY = e.clientY;
x = cursorX;
y = cursorY;
}
function showBox() {
ctx.beginPath();
ctx.arc(x,y,20,0,2*Math.PI);
ctx.stroke();
console.log(x,y);
outer.addEventListener("mousemove",getMousePos);
outer.addEventListener("mousemove",showBox)
outer.addEventListener("mouseup",removelisteners);
}
function removelisteners() {
outer.removeEventListener("mousemove",getMousePos);
outer.removeEventListener("mousemove",showBox)
}
outer.addEventListener("mousedown",getMousePos);
outer.addEventListener("mousedown",showBox);
;
Youu need to attach events for mousemove when mousedown occurs, similarly remove those events on mouseup

canvas based color picker on another canvas element

i have made a canvas having width and height of the window.i also made a color picker based on canvas which has a onmousemove event to get pixel information so that i can use that color to draw on my main canvas.individually the onmousemove for picker works but as soon as i put it on the corner side and gave it a fixed position accroding to my main drawing canvas, it's mouse event doesnt work.even i can draw beneath the color picker.i tried to set a z-index property for the color picker ,though it did'nt work.how can i solve this problem and make my picker work fine
hope i make my problem clear :(
if you run my code i hope you will understand the problem
<html>
<head>
<title>a drawing board</title>
</head>
<body style="margin:0;">
<script>
var radius=10;
var colorit="";
var lines;
var x,y;
var cna=false;
var i=0;
function canvloder(){
var canvas=document.getElementById("mycanvas");
canvas.width=window.innerWidth;
canvas.height=window.innerHeight;
canvas.style.backgroundColor="yellow";
}
function nowdraw(e){
cna=true;
}
function drawit(e){
if(cna){
var ctx=document.getElementById("mycanvas").getContext("2d");
x=e.clientX;
y=e.clientY;
if(i==0){
ctx.lineWidth=2*radius;
ctx.lineTo(x,y);
ctx.stroke();
}
if(i>0){
ctx.fillStyle=colorit;
ctx.beginPath();
ctx.arc(x,y,radius,0,2*Math.PI);
ctx.fill();
i=0;
}
ctx.fillStyle=colorit;
ctx.beginPath();
ctx.arc(x,y,radius,0,2*Math.PI);
ctx.fill();
ctx.lineWidth=2*radius;
ctx.strokeStyle=colorit;
ctx.beginPath();
ctx.moveTo(x,y);
}
}
function cannotdraw(){
cna=false;
i++;
}
window.onmousedown=nowdraw;
window.onmousemove=drawit;
window.onmouseup=cannotdraw;
function pencolor( colname){
colorit=colname;
}
function therad(capture){
if(capture=="increase"){
radius++;
}
if(capture=="decrease"){
radius--;
}
}
function gotClicked(val){
radius=val;
}
function itsmycanvas(){
var newCanvas = document.createElement('canvas');
var k=0,j=0,a=255,r=0;g=0;
newCanvas.width = 256;
newCanvas.height = 256;
newCanvas.style.position="fixed";
newCanvas.style.top="30px";
newCanvas.style.right="0px";
newCanvas.style.border ='2px solid black';
newCanvas.style.zIndex="2000";
for(r=0;r<256;r++){
for(g=0;g<256;g++){
var context = newCanvas.getContext('2d');
context.beginPath();
context.moveTo(k,j);
context.strokeStyle = 'rgb(' + r + ', ' + g + ','+a+')';
context.lineTo(k+90,j);
context.stroke();
context.closePath();
j++;
if(j==256){
if(k<=256-90){
k=k+90;
}
j=0;
}
a--;
if(a==0){a=150;}
}
}
var d=document.body.appendChild(newCanvas);
d.addEventListener("mouseover",myfunc,false);
}
function myfunc(e) {
var imageData = context.getImageData(e.clientX, e.clientY, 1, 1);
var red = imageData.data[0];
var green = imageData.data[1];
var blue = imageData.data[2];
var alpha = imageData.data[3];
alert(red+" "+green+" "+blue);
}
window.onload=canvloder;
</script>
<canvas id="mycanvas"></canvas>
<div style="position:fixed;top:0px;background-color:grey;display:block;width:100%;">
<div style="float:right;left:50px;">Radius <span title="increase width"style="background-color:white;padding:5px;margin-right:5px;" onCLick="therad('increase');"> + </span><span title="decrease width" style="padding:5px;background-color:white;margin-right:5px;" onClick="therad('decrease');"> - </span></div>
<div title="red" style="background-color:red;width:30px;height:30px;border-radius:30px;float:left;" onClick="pencolor('red');"></div>
<div title="black"style="background-color:black;width:30px;height:30px;border-radius:40px;float:left;" onClick="pencolor('black');"></div>
<div title="pink"style="background-color:pink;width:30px;height:30px;border-radius:40px;float:left;" onClick="pencolor('pink');"></div>
<div title="green"style="background-color:green;width:30px;height:30px;border-radius:40px;float:left;" onClick="pencolor('green');"></div>
<div title="eraser"style="background-color:white;width:30px;height:30px;border-radius:40px;float:left;text-align:centre;" onClick="pencolor('yellow');">clr</div>
<div title="blue"style="background-color:blue;width:30px;height:30px;border-radius:40px;float:left;" onClick="pencolor('blue');"></div>
</div>
<select style="position:fixed;top:0px;left:300px;">radius
<option onClick="gotClicked(15);">15px</option>
<option onClick="gotClicked(10);" selected>10px</option>
<option onClick="gotClicked(6);">8px</option>
<option onClick="gotClicked(5);">5px</option>
<option onClick="gotClicked(3);">3px</option>
</select>
<input type="button" onClick="itsmycanvas();" value="SHOW CANVAS" style="position:fixed;top:400px;right:0px;">
</body>
</html>
jsfiddle
(fiddle not working as it should be :\don't know what's wrong )
I removed the body tag from html and add the option no warp in body(option of fiddle)
it seems working
jsfiddle

Toggle Onclick Issue in Javascript

Simply put, I'm trying to toggle a button to make a line bold (or not). I read a few questions here similar to this problem, but the solutions haven't helped me. Here's my code:
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<div id="DrawLineDiv">
<canvas id="DrawLineCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('DrawLineCanvas');
var context = canvas.getContext('2d');
// Use beginPath() to declare that a new path is to be drawn
context.beginPath();
// Place the drawing cursor at the desired point
context.moveTo(100, 150);
// Determine where to stop drawing
context.lineTo(450,50);
//Draw the line
context.stroke();
</script>
</div>
<script>
var canvas = document.getElementById("DrawLineCanvas");
//var context = canvas.getContext('2d');
function toggleLineBold(button) {
var button;
if (button == "BoldNow") {
context.lineWidth = 15;
context.stroke();
document.getElementById("BoldLineButton").onclick = function(){
toggleLineBold('Regular');
};
} else {
context.lineWidth = 1;
context.stroke();
document.getElementById("BoldLineButton").onclick = function(){
toggleLineBold('BoldNow');
};
return;
};
};
</script>
<div id="BoldLineButton" style="height:50px; width:120px; border:2px solid #6495ed; background-color:#bcd2ee; border-radius:10px; margin-left: 5px; text-align:center" onclick="toggleLineBold('BoldNow')">
<br/>Toggle Bold Line<br/>
</div>
</body>
</html>
The line changes to bold, but triggers an error in the javascript at the line trying to change the onclick event. I know I've got something wrong, I'm just not sure what.
Thank's in advance for your assistance.
LIVE DEMO
HTML:
<canvas id="DrawLineCanvas" width="578" height="200"></canvas>
<button id="BoldLineButton">Line size: <b>1</b></button>
JS:
var doc = document,
canvas = doc.querySelector('#DrawLineCanvas'),
boldBtn = doc.querySelector('#BoldLineButton'),
ctx = canvas.getContext('2d'),
size = [1, 3, 5, 10, 15], // use only [1, 15] if you want
currSize = 0; // size[0] = 1 // Index pointer to get the value out of the
// size Array
function draw(){
canvas.width = canvas.width;
ctx.beginPath();
ctx.moveTo(100, 150);
ctx.lineTo(450,50);
ctx.lineWidth = size[currSize]; // Use currSize Array index
ctx.stroke();
}
draw();
function toggleLineBold() {
++currSize; // Increase size and
currSize %= size.length; // loop if needed.
boldBtn.getElementsByTagName('b')[0].innerHTML = size[currSize];
draw();
}
boldBtn.addEventListener("click", toggleLineBold);

HTML5 responsive canvas: resizing the browser canvas draw disappear

I want to make a responsive canvas using size in percentage and once user will resize the window the canvas adjust relatively.
I am able to scale the canvas by using below code but the only problem is as i scale the window size the mouse drawing disappear.
<style>
body{margin:0px;padding:0px;background:#a9a9a9;}
#main{
display:block;
width:80%;
padding:50px 10%;
height:300px;
}
canvas{display:block;background:#fff;}
</style>
</head>
<body>
<div id="main" role="main">
<canvas id="paint" width="100" height="100">
< !-- Provide fallback -->
</canvas>
</div>
<script>
var c = document.getElementById('paint');
var ctx = c.getContext('2d');
var x = null;
var y;
c.onmousedown = function(e){
x = e.pageX - c.offsetLeft;
y = e.pageY - c.offsetTop;
ctx.beginPath();
ctx.moveTo(x,y);
}
c.onmouseup = function(e){
x=null;
}
c.onmousemove = function(e){
if(x==null) return;
x = e.pageX - c.offsetLeft;
y = e.pageY - c.offsetTop;
ctx.lineTo(x,y);
ctx.stroke();
}
$(document).ready( function(){
//Get the canvas &
var c = $('#paint');
var container = $(c).parent();
//Run function when browser resizes
$(window).resize( respondCanvas );
function respondCanvas(){
c.attr('width', $(container).width() ); //max width
c.attr('height', $(container).height() ); //max height
//Call a function to redraw other content (texts, images etc)
}
//Initial call
respondCanvas();
});
</script>
Thanks.
Dealing with contents when resizing a canvas
If you resize the canvas, the drawn content is always erased. That's how canvas behaves.
You can either redraw the content after resizing or you can save the content as image data and restore after resizing (see canvas.toDataURL).
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/V6SVz/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:10px; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// draw some content
ctx.lineWidth=3;
ctx.fillStyle="blue";
ctx.strokeStyle="red";
ctx.rect(50,50,100,50);
ctx.fill();
ctx.stroke();
ctx.font="14px Verdana";
ctx.fillStyle="white";
ctx.fillText("Scale Me",65,75);
function saveResizeAndRedisplay(scaleFactor){
// save the canvas content as imageURL
var data=canvas.toDataURL();
// resize the canvas
canvas.width*=scaleFactor;
canvas.height*=scaleFactor;
// scale and redraw the canvas content
var img=new Image();
img.onload=function(){
ctx.drawImage(img,0,0,img.width,img.height,0,0,canvas.width,canvas.height);
}
img.src=data;
}
$("#resizer").click(function(){ saveResizeAndRedisplay(1.5); });
}); // end $(function(){});
</script>
</head>
<body>
<button id="resizer">Click to resize the canvas</button><br/>
<canvas id="canvas" width=200 height=150></canvas>
</body>
</html>
c.attr('width', $(container).width() ); //max width
c.attr('height', $(container).height() ); //max height
the above code is equivalent to clearRect which is used to clear the canvas .so you cannot adjust the width and height if you want to retain what was drawn previously.
as a solution you can create a new canvas with required width and draw the content of previous canvas using drawImage(c) c is the canvas object .then you have to delete the canvas
I also had the same issue that your are facing in mu application, and after reading about it i came to this conclusion that the behavior of the canvas element is such that it clears itself after re-sizing, the only fix for this is to add a listener for the window re-size event and redraw the canvas when the event if fired.
$(window).resize(function(e) {
// function to redraw on the canvas
});
$(document).ready(function(e){
var c = $('#example'); // getting the canvas element
var ct = c.get(0).getContext('2d');
var container = $(c).parent();
$(window).resize( respondCanvas ); //handling the canvas resize
function respondCanvas(){
// makign the canvas fill its container
c.attr('width', $(container).width() ); //max width
c.attr('height', ($(container).height() -20 )); //max height
}
respondCanvas();
make_image('images/india.png',1,1);
}
Hope it helps.
Source
I've created a jQuery plugin that handles HTML5 canvas resizing. It was built to bridge the gap between mobile and desktop users. It is still a WIP but it is extensible, and has some basic drawing functions built in.
http://trsanders.github.io/responsive-sketchpad/
below is the code what I was trying to do:
<head>
<style>
#main {
display:block;
width:80%;
height:300px;
background:#e0e0e0;
}
canvas {
display:block;
background:#fff;
border:1px solid red;
}
</style>
<script>
$(function(){
var container=document.getElementById("main");
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// draw some content
//alert(canvas.width);
var w=$(container).width();
var h=$(container).height();
$(window).resize( saveResizeAndRedisplay );
function saveResizeAndRedisplay(){
// save the canvas content as imageURL
var data=canvas.toDataURL();
// resize the canvas
canvas.width = $(container).width();
canvas.height = $(container).height();
//alert($(container).width());
// scale and redraw the canvas content
var img=new Image();
img.onload=function(){
ctx.drawImage(img,0,0,img.width,img.height);
}
img.src=data;
}
saveResizeAndRedisplay();
});
</script>
</head>
<body>
<div id="main" role="main">
<canvas id="canvas" width=200 height=150></canvas>
</div>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = null;
var y;
canvas.onmousedown = function(e){
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
ctx.beginPath();
ctx.moveTo(x,y);
}
canvas.onmouseup = function(e){
x=null;
}
canvas.onmousemove = function(e){
if(x==null) return;
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
ctx.lineTo(x,y);
ctx.stroke();
}
</script>
</body>
I use this method:
var context = document.getElementById('paint').getContext('2d');
var canvas = context.canvas;
function responsive(width){
var p = width / canvas.width;
canvas.width *= p;
canvas.height *= p;
var scaleFactor = context.scaleFactor || 1;
context.scale(p * scaleFactor, p * scaleFactor);
context.scaleFactor = p * scaleFactor;
}
var mq = window.matchMedia("(min-width: 735px)");
mq.addListener(applyChanges);
applyChanges();
function applyChanges(){
if(!mq)
responsive(350);
else
responsive(735);
}
I had the same problem. My solution is using CSS3's property zoom to the parent's container of the canvas:
<div id="parent_div">
<div id="constructor_div">
<canvas width="600" height="900">
</div>
</div>
<script>
constructor_zoom();
$(window).resize(function() {
constructor_zoom();
});
function constructor_zoom()
{
var parent_width = $('#parent_div').width();
var item_width = $('#constructor_div').width();
var coef = 0.1;
$('.constructor_image').css('zoom', parent_width/item_width - coef);
}
</script>
coef - coefficient to make indents of the canvas from the parent's borders. You may make it zero.
I hope it helps to somebody :-)

Categories