I have already searched this site and many others for an answer to this question, but according to every site (including this one and w3schools) the following should work to draw a line using canvas in HTML5.
var c=document.getElementById("drawBox");
var ctx=c.getContext("2d");
ctx.strokeStyle=document.getElementById("lineColor").value;
ctx.fillStyle=document.getElementById("fillColor").value;
ctx.lineWidth=document.getElementById("lineWidth").value;
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
Keep in mind the above lines are snippets from my code, not the full code itself, that is below.
I am trying to write a simple drawing program for an assignment I have, but for some reason (and I have tested different ways of doing this) it simply won't draw the line. It's not throwing any errors, it just won't draw the line. I am using Google Chrome (the only browser you can thoroughly trust using html5, to my understanding). I have tested the code below so as to ensure that the logical branches are, in fact, being executed. In fact, everything is executed perfectly, up until the actual ctx.stroke(); function. Again, it doesn't error, but it simply won't draw the line. The mouseup and mouseout functions are also working fine, as I tested it with other code that I knew would work. Below is the code I am working with:
HERE IS THE REVISED CODE (STILL DOESN'T DRAW THOUGH, DESPITE ALL THE GOOD HELP SO FAR)
$(document).ready(function (){
///////////////////////////////////////////
var c=document.getElementById("drawBox");
var ctx=c.getContext("2d");
var x=0;
var y=0;
var position="";
var rangeValue=1;
var x1=0;
var y1=0;
var startDraw=false;
var x2=0;
var y2=0;
$('#drawBox').mousemove(function (){
x=window.event.clientX;
y=window.event.clientY;
position=x + ", " + y;
document.getElementById("check").innerHTML=position;
});
$("#lineWidth").mousemove(function (){
rangeValue = document.getElementById("lineWidth").value;
$("#rangeValueContainer").html(rangeValue);
});
$("#drawBox").mouseout(function (){
startDraw=false;
});
$("#drawBox").mousedown(function (){
startDraw=true;
x1=window.event.clientX;
y1=window.event.clientY;
ctx.strokeStyle=document.getElementById("lineColor").value;
ctx.fillStyle=document.getElementById("fillColor").value;
ctx.lineWidth=document.getElementById("lineWidth").value;
ctx.moveTo(x1, y1);
});
///
$("#drawBox").mouseup(function (){
if (startDraw)
{
x2=window.event.clientX;
y2=window.event.clientY;
//$("p").html(document.getElementById("fillColor").value);
ctx.lineTo(x2, y2);
ctx.stroke();
startDraw = false;
}
});
///
/*if (document.getElementById("shapeSelect").value == "line")
{
$("#drawBox").mouseup(function (){
x2=window.event.clientX;
y2=window.event.clientY;
//$("p").html(document.getElementById("lineColor").value);
ctx.lineTo(x2, y2);
ctx.stroke();
});
}
if (document.getElementById("shapeSelect").value == "square")
{
$("p").html(document.getElementById("fillColor").value);
}
if (document.getElementById("shapeSelect").value == "circle")
{
}
}); */
$("#eraseBtn").click(function (){
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, ctx.width, ctx.height);
ctx.restore();
});
});
Also, some sites say to use beginPath() others say to use beginPath() and closePath(), while others (namely, w3schools) doesn't say to use either? Are they necessary? What is their point? Do I need them at all, or under certain circumstances? I must get this program to draw squares and circles, as well, in the end.
Any help would be greatly appreciated.
Sorry if this post is a little sloppy, I tried, but this is my first post, and I don't think the part of this site that recognizes that something is code, is picking up jquery.
I had to manually enter a lot of linebreaks just to get it to look as bad as it does XD
Also, it is probably important to mention that I have (as I ALWAYS do before testing) cleared the cache and even always use ctrl+f5 to ignore the cache on load.
Thanks
Okay Here is the HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Canvas Drawer</title>
<base href="index.htm"/>
<link rel="shrotcut icon" href="/paintbrush.ico" type="image/x-icon" />
<link href="_Styling.css" rel="stylesheet" type="text/css" media="screen" />
<script type="text/javascript" src="jquery.1.7.2.js"></script>
<script type="text/javascript" src="_Operation.js"></script>
</head>
<body>
<table id="tableContainer">
<tr>
<td colspan="2">
</br>
<span id="programTitle">
Painter 0.0
</span></br>
</td>
</tr>
<tr>
<td colspan="2">
<canvas id="drawBox">Your browser does not support the HTML5 canvas tag.</canvas>
</td>
</tr>
<tr>
<td style="text-align: left;">
<span>
Cursor Position:
</span>
</td>
<td style="text-align: right;">
<span id="checkPosition">
<span id="check">0, 0</span>
</span>
</td>
</tr>
</table>
<p>
Draw:
<select id="shapeSelect" value="line">
<option value="line">Line</option>
<option value="square">Square</option>
<option value="circle">Circle</option>
</select>
</p>
<p>
Select Line Color: <input type="color" id="lineColor"/>
</p>
<p>
Select Fill Color: <input type="color" id="fillColor"/>
</p>
<p>
<span style="text-decoration: underline;">Line Width:</span></br>
<input type="range" id="lineWidth" min="1" max="30" value="10"/></br>
<span id="rangeValueContainer">10</span></br>
</p>
<p>
<input id="eraseBtn" type="button" value="Erase"/>
</p>
</body>
You have a problem with scopes.
Move all your script under one $(document).ready(),
ie,
$(document).ready(function (){
var c=document.getElementById("drawBox");
...
$('#drawBox').mousemove(function (){
...
});
etc.
});
By surrounding each code snippet in a separate function(){} block you are isolating the variables within them.
It also appears as if your canvas does not have any size. Try setting its size as well,
<canvas id="drawBox" width="200px" height="200px">Your browser does not support the HTML5 canvas tag.</canvas>
Your drawing is correct, but there are two problems -
You added several separate $(document).ready functions, each with
separate scope which is why none of your variables survived
You didn't use the jQuery event object to get the client position -
see the jquery api
Here's a working version jsfiddle
Ok here goes. First of all, never assume that your code is correct. If its not working, your code is obviously not correct. In this case it is not a bug. There are 2 things wrong with your current implementation:
Your positioning is way off. I have a sneaking suspicion that your line was not visible as it was being rendered far off of the canvas.
You need to use .beginPath() and .closePath() this will help prevent unpredictable behavior in your path drawing.
SOLUTION The problem is that you are defining the dimensions of your canvas in the css and not the canvas element itself.
Working solution http://jsfiddle.net/crbHg/9/
Related
This is the first time I use stackoverflow to ask for help, so if there is anything I have done wrong please tell me. And I am not a native English speaker, so hope you understand my problem.
I was intend to create a webpage that can draw lines. There isn't any big issues. However, I realize that each time I use stroke() to draw a new lines, the previous lines become thicker. Can this problem be solved?
<html>
<body>
<div id="coord"></div>
<canvas id="Maintheme" height="800" width="1000"></canvas>
</body>
<script>
var canvas=document.getElementById("Maintheme");
var context=canvas.getContext('2d');
var coordinates;
var Xcoor;
var Ycoor;
var lineboolean=false;
canvas.width=window.innerWidth;
canvas.height=window.innerHeight;
canvas.addEventListener('mousemove',function(evt){
coordinates=evt.clientX+" "+evt.clientY;
Xcoor=evt.clientX;
Ycoor=evt.clientY;
document.getElementById("coord").innerHTML=coordinates;})
canvas.addEventListener('click',function(){
if (lineboolean==false){
context.moveTo(Xcoor,Ycoor);
lineboolean=true;
}
else{
context.lineTo(Xcoor,Ycoor);
context.stroke();
lineboolean=false;
}
})
</script>
</html>
On my website http://www.ruigrok-nederland.nl/ i cant select text.
Its working fine on Chrome and Firefox.
How is this possible?
I am 100% sure it is not a configuration in Internet explorer, because it works well on other pages.
Thanks
On your page I am getting an error every time I click the left mouse button or moving the cursor. The onclick error is stopping IE from dealing with what is happening when you and click-drag to select the text.
It is possible to select the text using keyboard shortcuts. If you fix the JavaScript errors that I mentioned above the page will start to work as desired.
your error exists here:
function mousePos (e) {
if (!mie) {
mouseX = e.pageX;
mouseY = e.pageY;
}
else {
mouseX = event.clientX + document.body.scrollLeft;
mouseY = event.clientY + document.body.scrollTop;
}
document.show.mouseXField.value = mouseX;
There is no document.show object. I don't know where you're getting this from/what sample could you got it from??? Also, you are mixing variables... your function is getting e as the parameter/variable event object, but you are using event in your else statement. That won't work since event is undefined.
document.show.mouseYField.value = mouseY;
If you don't have a good reason otherwise, you can use jQuery to do this, since one of the goals and benefits of jQuery is cross-browser functionality:
<html lang="en">
<head>
<meta charset="utf-8">
<title>select demo</title>
<style>
p {
color: blue;
}
div {
color: red;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Click and drag the mouse to select text in the inputs.</p>
<input type="text" value="Some text">
<input type="text" value="to test on">
<div></div>
<script>
$( ":input" ).select(function() {
$( "div" ).text( "Something was selected" ).show().fadeOut( 1000 );
});
</script>
</body>
</html>
am making a Createjs and html5 project in which I am drawing a shape(Red circle), when I click over the circle it gives alert. It works fine on all desktops and android phones. Except when I open this in a windows phone it works fine on the normal screen but when I zoom the screen it loses it working, an alert is shown when I click anywhere on the screen(maybe where the co-ordinates of the shape resides) but not when I click over the shape(Circle),,
Your help is appreciated
my demo.html
<!DOCTYPE html>
<html>
<head><title></title>
<script type="text/javascript" src="createjs-2013.12.12.min.js"></script>
<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
<script type="text/javascript">
function init() {
var stage = new createjs.Stage("demoCanvas");
var circle = new createjs.Shape();
createjs.Touch.enable(stage);
circle.graphics.beginFill("red").drawCircle(0, 0, 50);
circle.x = 100;
circle.y = 100;
circle.addEventListener("click", function(evt) { /*$("span#log").text(circle.x);*/ alert('clicked'); });
stage.addChild(circle);
stage.update();
}
</script>
</head>
<body onLoad="init();">
<span id="log"></span>
<br>
<canvas id="demoCanvas" width="500" height="300">
alternate content
</canvas>
</body>
</html>..
Here's the project
Not sure if this is relevant as haven't looked at sample code, but I think createjs.Touch.enable works on Stage instances rather than DisplayObjects
See here
I do alot of Research over this topic, and at the end i came to this point that this the
BUG in IE11 . Hope Microsoft helps to solve this.
Im trying to do a composite operation on layers using KineticJS.
Everything works fine in Chrome, but nothing shows for firefox, or IE10
The code runs through without any errors.
You can see the issue here:
http://clients.lilodesign.com/Lilo/Kinetic/
Chrome you should see a circle with a partial bit of the standard MS Blue Trees image showing through. In Firefox and IE10 you just get a blank screen.
You can view the code by viewing the source. Its all in-line and a very simple example to show the issue.
If you remove the following line:
ctx.globalCompositeOperation = "destination-atop";
Then you see the blue trees image with the ellipse on top of it as expected in all three browsers, so the code does "work".
Has anyone else experienced this and found a workaround?
I have searched and tried a couple of suggested solutions such as:
shape intersection with KineticJS
But all these still only seem to work in Chrome.
Any help or pointers would be appreciated.
Thanks
Tyrone.
We used to be able to cheat by grabbing the context of a layer, but now it’s unreliable (as you’ve discovered).
You can still get verrrrry hacky and do it like this: : http://jsfiddle.net/m1erickson/6fTQU/
But don’t ! (Even this hack doesn’t actually work on images with transparent pixels).
Instead, do it the official way by creating a Kinetic custom Shape Object.
Kinetic Shape gives you an official canvas and context to work with.
As a result, the globalCompositeOperation works fine (reliably!).
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/LtxEe/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Prototype</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.5.1.min.js"></script>
<style>
body{ background-color: ivory; }
#container{
border:solid 1px #ccc;
margin-top: 10px;
width:300px;
height:300px;
}
</style>
<script>
$(function(){
var stage = new Kinetic.Stage({
container: 'container',
width: 300,
height: 300
});
var layer = new Kinetic.Layer();
stage.add(layer);
var img=new Image();
img.onload=function(){
buildLayer(img);
}
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/KoolAidMan.png";
function buildLayer(img){
var myShape=new Kinetic.Shape({
drawFunc:function(canvas){
var ctx=canvas.getContext();
ctx.beginPath();
ctx.drawImage(img,0,0);
ctx.globalCompositeOperation="destination-atop";
ctx.arc(150,150,60,0,Math.PI*2,false);
ctx.closePath();
ctx.fill();
canvas.fillStroke(this);
},
x:0,
y:0,
width:img.width,
height:img.height
});
layer.add(myShape);
layer.draw();
}
}); // end $(function(){});
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
I am working through the HTML5 canvas tutorial on the following website:
Mozilla Developers.
In this tutorial, they say that you can use a canvas element as the backdrop of another canvas element. I have tried to do exactly that with the following html page. Unfortunately, the debugger in chrome says failed to load resource. Am I referencing the source canvas object the correct way in the function draw2()?:
<html>
<head>
<title>CANVAS TESTING</title>
<script type="text/javascript">
function draw()
{
var ctx = document.getElementById('tutorial').getContext('2d');
ctx.translate(0,document.getElementById('tutorial').height);
ctx.scale(1,-1)
// Create gradients
var lingrad = ctx.createLinearGradient(0,0,0,150);
lingrad.addColorStop(0, '#fff');
lingrad.addColorStop(0.5, '#66CC00');
lingrad.addColorStop(0.5, '#fff');
lingrad.addColorStop(1, '#00ABEB');
var lingrad2 = ctx.createLinearGradient(0,50,0,95);
lingrad2.addColorStop(0.25, 'rgba(0,0,0,0)');
lingrad2.addColorStop(0.75, '#000');
// assign gradients to fill and stroke styles
ctx.fillStyle = lingrad;
ctx.strokeStyle = lingrad2;
// draw shapes
ctx.fillRect(10,10,130,130);
ctx.strokeRect(50,50,50,50);
}
function draw2()
{
ctx=document.getElementById('canvas').getContext('2d');
img = new Image();
img.onload = function()
{
ctx.drawImage(img,0,0);
}
img.src = document.getElementById('tutorial');
}
</script>
</head>
<body onload="draw()">
<p>This is a test of canvas element.</p>
<canvas id="tutorial" width="400" height="400" style="background-color: black"></canvas>
<br /><br />
<canvas id="canvas" width="400" height="400" style="background-color: black"></canvas>
<p>
<input type="button" onclick="draw2()" value="Draw!" />
</p>
</body>
Your solution is kinda correct but you're making it waaaay more complicated than it has to be.
All you have to do is this, nothing any fancier:
var tut = document.getElementById('tutorial');
ctx.drawImage(tut,0,0); // just put in the canvas you want to draw!
Here's a live jsfiddle example if you need more detail
Ok, I just found the answer to my question.
going off the function in Draw2(), I needed to set my img.src to the following:
img.src = document.getElementById('tutorial').toDataURL();
What this does is returns the base64 encoded data string of the png image of the canvas element.