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>
Related
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'm also curious to know if this is a best practice.
I load a sprite map:
canvas = $('#GameCanvas')[0];
context = canvas.getContext('2d');
// load sprite map
spriteMap = new Image();
spriteMap.src = "resources/spritemap.png";
Now I've loaded my sprites, I want to draw them on the screen. I can do so by using context.drawImage(..) but:
I don't know if this is the best way, instead of just extracting each image I want and storing them separately eg. var playerCharacter = [cut the image out of the sprite map]
I want to colorise the images. If I pull out a 'white' sprite, I may then want to colorise it red, green, etc. I don't know how to do this yet, but it will probably require creating a new colorised Image so I'd have to pull it out of the spritemap anyway. I don't want to be recolorising constantly.
Any idea the best way of doing this?
Performance using sprites
Phrogz has some useful FPS tests for CSS vs Canvas here: Efficiency of <canvas> and <div>s They are live tests so you can run them in the environments you want to test.
Recoloring sprites
If you want to quickly take your white sprite and create red, green and blue sprites from it, you can use globalCompositeOperation=”source-in” to do that with very little work. Just use an image editor to create a cutout of the part of the image you want to recolor. Then use the code below to automatically create different colored sprites. I did the mask below in Photoshop using the magic want tool – 2 minutes tops!
Original Fish + Mask = Green Fish
Of course, you can create any color you want...even patterns instead of solid colors!
Here’s code. You will probably have to create your own image and mask because of CORS – stupid CORS !!
<!doctype html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
canvas{border:1px solid red;}
#wrapper{ position:relative;}
#overlay,#base{ position:absolute; top:0; left:0;}
</style>
<script>
$(function(){
var canvas=document.getElementById("overlay");
var ctx=canvas.getContext("2d");
var img=new Image();
img.onload=function(){
ctx.drawImage(img,0,0,img.width,img.height,0,0,overlay.width,overlay.height);
}
img.src="http://dl.dropbox.com/u/139992952/stackoverflow/fish%20overlay.png";
function draw(red,green,blue) {
ctx.save();
ctx.globalCompositeOperation = 'source-in';
ctx.fillStyle="rgb("+red+","+green+","+blue+")";
ctx.beginPath();
ctx.rect(0,0,overlay.width,overlay.height);
ctx.fill();
ctx.restore();
}
$("#red").click(function(){ draw(255,0,0); });
$("#green").click(function(){ draw(0,255,0); });
$("#blue").click(function(){ draw(0,0,255); });
});
</script>
</head>
<body>
<button id="red">Red Fish</button>
<button id="green">Green Fish</button>
<button id="blue">Blue Fish</button>
<div id="wrapper">
<img id="base" src="http://dl.dropbox.com/u/139992952/stackoverflow/fish.png" width=350 height=250>
<canvas id="overlay" width=350 height=250></canvas>
</div>
</body>
</html>
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/
I heard that drawing abilities will be supported by Web 2.0
Tried to find something in Internet about, nothing really clear. Could you please point me into something that allows (or will allow in future) to draw in HTML?
For example: I want to have ability draw few hexagons in different color on the page.
Thanks.
P.S. Sorry if question is a little bit "stupid", but I can't make it more smart.
A quick exemple of what you want to do:
<html>
<head>
<title>Hexagon canvas tutorial</title>
<script type="text/javascript">
function draw(){
//first let's get canvas HTML Element to draw something on it
var canvas = document.getElementById('tutorial');
//then let's see if the browser supports canvas element
if (canvas.getContext){
var ctx = canvas.getContext('2d');
//Pick Hexagon color, this one will be blue
ctx.fillStyle = "rgb(0, 0, 255)";
//let's start a path
ctx.beginPath();
//move cursor to position x=10 and y=60, and move it around to create an hexagon
ctx.moveTo(10,60);
ctx.lineTo(40,100);
ctx.lineTo(80,100);
ctx.lineTo(110,60);
ctx.lineTo(80,20);
ctx.lineTo(40,20);
//fill it and you got your first Hexagon
ctx.fill();
//This one will be green, but we will draw it like the first one
ctx.fillStyle = "rgb(0, 255, 0)";
ctx.beginPath();
ctx.moveTo(110,160);
ctx.lineTo(140,200);
ctx.lineTo(180,200);
ctx.lineTo(210,160);
ctx.lineTo(180,120);
ctx.lineTo(140,120);
ctx.fill();
}
}
</script>
<style type="text/css">
canvas { border: 1px solid black; }
</style>
</head>
<body onload="draw();">
<canvas id="tutorial" width="300" height="300"></canvas>
</body>
</html>
What you're talking about is most likely the HTML5 Canvas element
I suspect you've been hearing about the Canvas Element. You can get started with it here: http://en.wikipedia.org/wiki/Canvas_element
Good luck!
I am trying to load a bitmap into the canvas following the example here.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HTML 5 Reports</title>
<script type="text/javascript">
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.onload = function(){
ctx.drawImage(img,0,0);
ctx.beginPath();
ctx.moveTo(30,96);
ctx.lineTo(70,66);
ctx.lineTo(103,76);
ctx.lineTo(170,15);
ctx.stroke(); }
img.src = 'worldmap1.bmp';
}
</script>
</head>
<body onload="draw()">
<canvas id="graph"></canvas>
</body>
</html>
Nothing is drawn in the browser when I view the page. No Errors Given.
Please tell me what I am doing wrong. Thanks!
I guess I should answer this question so I can close it. That is what it seems to say on meta.stackoverflow.com
Ok I forgot the semi-colon after draw(); and canvas id needs to be "canvas" instead of "graph". Solved my own problem =) I feel smart now =) Thanks for the help all. – EddieC 2 mins ago edit.
I have no experience with Canvas, but I would be surprised if BMP files were supported... Try a JPG, PNG or GIF file, those are reliably supported across all browsers.
If its not bitmap related per the other posts... are you sure img.src is a valid path to the file?