how to set div background as canvs - javascript

Here is my code:
<!DOCTYPE html>
<html>
<body>
<div id='rect' style='width:200px;height:200px;border:1px solid red'>
</div>
<canvas id="myCanvas" style="border:1px solid #d3d3d3;">
<script>
patternStyle = document.getElementById("myCanvas");
var patternContext = patternStyle.getContext('2d');
patternStyle.width = 6;
patternStyle.height = 6;
patternContext.globalAlpha = 10;
patternContext.fillStyle = 'white';
patternContext.rect(0, 0, 6, 6);
patternContext.fillRect(0, 0, 6, 6);
patternContext.strokeStyle = 'red';
patternContext.lineWidth = 2;
patternContext.beginPath();
patternContext.moveTo(3, -3);
patternContext.lineTo(-3, 3);
patternContext.moveTo(0, 6);
patternContext.lineTo(6, 0);
patternContext.moveTo(9, 3);
patternContext.lineTo(3, 9);
patternContext.stroke();
</script>
</body>
</html>
I need to set the rect(id of the div) background image as myCanvas(id of the canvas). How can I achieve this?
Find the jsfiddle link here: http://jsfiddle.net/yLL48one/

Check out the updated fiddle: http://jsfiddle.net/yLL48one/1/
The key lines are:
dataUrl = document.getElementById('myCanvas').toDataURL();
document.getElementById('rect').style.background='url('+dataUrl+')';

Related

HTML5 Canvas object oriented

Hi im trying to create a stock bar chart using html5 canvas, first I've decided to create bar object with different methods but can't make it work. Generated bar object does not appears
This is my code:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="1024" height="600" style="border:3px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var context = document.getElementById("myCanvas").getContext("2d");
function Bar(time,open,high,low,close,dir){
vertcord=time
openC=open
highC=high
lowC=low
closeC=close
line_width=8
bar_col='#ff0000'
if (dir==1){
bar_col='#ace600'
}
this.moveTo(vertcord,highC);
this.lineTo(vertcord,lowC);
this.moveTo(vertcord-line_width/2,closeC);
this.lineTo(vertcord+30,closeC);
this.lineWidth = line_width
this.strokeStyle = bar_col;
this.stroke();
}
for (i=0; i < 300; i++) {
tempShape = new Bar(450+i,0,200,100,150,1);
tempShape.drawToContext(context);
}
</script>
</body>
</html>
function Bar(time,open,high,low,close,dir){
this.vertcord = time;
this.openC = open;
this.highC = high;
this.lowC = low;
this.closeC = close;
this.line_width = 8;
this.bar_col = '#ff0000';
if (dir ==1 ) {
this.bar_col = '#ace600';
}
this.drawToContext = function(ctx) {
ctx.moveTo(this.vertcord, this.highC);
ctx.lineTo(this.vertcord, this.lowC);
ctx.moveTo(this.vertcord-this.line_width/2,this.closeC);
ctx.lineTo(this.vertcord+30,this.closeC);
ctx.lineWidth = this.line_width
ctx.strokeStyle = this.bar_col;
ctx.stroke();
}
}
var context = document.getElementById("myCanvas").getContext("2d");
for (i=0; i < 300; i++) {
tempShape = new Bar(450+i,0,200,100,150,1);
tempShape.drawToContext(context);
}
<canvas id="myCanvas" width="1024" height="600" style="border:3px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
I think this is how it supposed to be.You better read a tutorial how to properly implement an object oriented pattern in JavaScript. And learn what "this" means in JavaScript.

Cell of a minesweeper board does not appear Html&CSS&JS

I am trying to creat a minesweeper board in Javascript, but first i tried to creat only one cell. this is my code. It was suppose to draw a cell from the 30px width and 30px height picture that i created ( cell.png ) but when i run the code i only see the canvas. What am i doing wrong?
<!DOCTYPE html>
<html>
<head>
<script>
var s = {
rows: 10,
col: 10,
width: 30,
height: 30,
};
var c;
window.onload = function(){
var canvas = document.getElementById("myCanvas");
c = canvas.getContext("2d");
// c.fillRect(50,50,300,300);
init();
}
var box;
function init(){
box = new Image();
box.src = "cell.png";
draw();
}
function draw(){
c.clearRect(0,0,400,400);
c.drawImage(box,10,10);
}
</script>
</head>
<body>
<div id="controls">
</div>
<div id="game">
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #c3c3c3;">
</canvas>
</div>
</body>
</html>
The problem you are experiencing is because your code is not waiting for the image to load before trying to draw it. You need to wait till it is loaded then call the drawing code, this can be done from the image's onload event
var s = {
rows: 10,
col: 10,
width: 30,
height: 30,
};
var c;
window.onload = function(){
var canvas = document.getElementById("myCanvas");
c = canvas.getContext("2d");
init();
}
var box;
function init(){
box = new Image();
//onload will be called once the image has loaded
box.onload = function(){
//Here you call draw.
draw();
};
box.src = "http://placehold.it/30x30"; //"cell.png";
}
function draw(){
c.clearRect(0,0,400,400);
c.drawImage(box,10,10);
}
<canvas width="200" height="200" id="myCanvas"></canvas>

Adding Click Event Handler onto Multiple Canvas

I am fairly new to javascript and HTML5, so excuse me if it turns out to be a silly mistake
I am drawing 3 canvas programmatically with some text and a rectangle and i want a click event on each one of them, also I need to know which canvas has been clicked, i wrote the following code but doMouseDown function is executed even without click
<canvas id="myCanvas1" width="452" height="80" style="border:0px solid #d3d3d3;"></canvas>
<canvas id="myCanvas2" width="452" height="80" style="border:0px solid #d3d3d3;"></canvas>
<canvas id="myCanvas3" width="452" height="80" style="border:0px solid #d3d3d3;"></canvas>
<script>
function init()
{
var rect = { w: 300, h: 60 };
var point = { x: 150, y: 10 };
for (var i = 1 ; i < 4 ; i++) {
var canvasStr = "myCanvas" + Number(i);
var c = document.getElementById(canvasStr);
var context = c.getContext("2d");
// text
context.font = "22pt Arial";
context.lineWidth = 2;
context.fillStyle = "#000000";
var studentStr = "Student " + Number(i);
context.fillText(studentStr, 5, 50);
// rectangle
context.strokeStyle = "black";
context.strokeRect(point.x, point.y, rect.w, rect.h);
context.fillStyle = "#00FF00";
context.fillRect(point.x, point.y, rect.w, rect.h);
c.addEventListener('mousedown', doMouseDown(canvasStr), false);
}
}
function doMouseDown(canvasStr)
{
alert(canvasStr);
}
init();
</script>
How can i fix it and know which canvas has been clicked (canvasStr in this case)
You can do it this way
c.addEventListener("mousedown", function () {
doMouseDown(canvasStr)
}, false);
and then write in that function
function doMouseDown(canvasStr) {
alert(canvasStr);
}
if you're attaching listeners in a loop, you have to create a closure, otherwise canvasStr will allways be == myCanvas3:
(function(str) {
c.addEventListener('mousedown', doMouseDown.bind(str), false);
}(canvasStr));
Then your callback should be:
function doMouseDown(e, canvasStr) {
alert(canvasStr);
}
First argument e is the Event object which is always passed to callbacks.
ADDED
There is no point in doing this:
var canvasStr = "myCanvas" + Number(i);
i is already a number and you are adding it to a string. Just write:
var canvasStr = "myCanvas" + i;
Another way is to wrap all 3 canvases in a container div and listen for events on the container
http://jsfiddle.net/m1erickson/g7fsS/
<div id="container">
<canvas id="myCanvas1" width="45" height="80"></canvas>
<canvas id="myCanvas2" width="45" height="80"></canvas>
<canvas id="myCanvas3" width="45" height="80"></canvas>
</div>
document.getElementById("container").addEventListener("click",function(e){
console.log(e.target.id);
},false);

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);

Why on dynamically created canvas context does not work?

Look: http://jsfiddle.net/MrHIDEn/QYL3t/
This code draws 3 boxes Reg,Green,Blue but context("2d") from Blue does do nothing. Why?
HTML:
<div id="divR">
<canvas id="cvsR" width="100" height="100" style="border:1px solid red"></canvas>
</div>
<div id="divG"></div>
<div id="divB"></div>
Javascript:
var cvsR = document.getElementById("cvsR");
var ctxR = cvsR.getContext("2d");
ctxR.fillStyle = "red";
ctxR.fillRect(0, 0, 50, 75);
var divG = document.getElementById("divG");
divG.innerHTML = '<canvas id="cvsG" width="100" height="100" style="border:1px solid green"></canvas>';
var cvsG = document.getElementById("cvsG");
var ctxG = cvsG.getContext("2d");
ctxG.fillStyle = "green";
ctxG.fillRect(0, 0, 50, 75);
// Dynamiclly
var divB = document.getElementById("divB");
var cvsB = document.createElement("canvas");
cvsB.width = 100;
cvsB.height = 100;
cvsB.style.border = "1px solid blue";
cvsB.id = "cvsB";
var ctxB = cvsB.getContext("2d");
ctxB.fillStyle = "blue";
ctxB.fillRect(0, 0, 50, 75);
divB.innerHTML = cvsB.outerHTML;
Your problem is here divB.innerHTML = cvsB.outerHTML;, with this code you aren't adding the canvas cvsB to divB but a can vas with the same html as cvsB. To add cvsB to the div just append it
divB.appendChild(cvsB);
http://jsfiddle.net/QYL3t/14/
I would append the canvas before reading the context, but it works without this, so this is just my personal preference:
cvsB.id = "cvsB";
divB.appendChild(cvsB);
var ctxB = cvsB.getContext("2d");
ctxB.fillStyle = "blue";
ctxB.fillRect(0, 0, 50, 75);

Categories