I want to write a processing.js script for my webpage, but my sketch doesn't show up. I included the following lines :
<canvas id="mycanvas'></canvas>
<script src="https://cdn.jsdelivr.net/processing.js/1.4.8/processing.min.js"></script>
<script>
var sketchProc = function(processingInstance) {
with (processingInstance) {
size(400, 400);
frameRate(30);
// ProgramCodeGoesHere
fill(255, 255, 0);
ellipse(200, 200, 200, 200);
noFill();
stroke(0, 0, 0);
strokeWeight(2);
arc(200, 200, 150, 100, 0, PI);
fill(0, 0, 0);
ellipse(250, 200, 10, 10);
ellipse(153, 200, 10, 10);
}};
// Get the canvas that Processing-js will use
var canvas = document.getElementById("mycanvas");
// Pass the function sketchProc (defined in myCode.js) to Processing's constructor.
var processingInstance = new Processing(canvas, sketchProc);
</script>
I don't see any error messages, so I don't know what's wrong.
Try this: in the first line, change id="mycanvas' to either id="mycanvas" or id='mycanvas' (don't mix them up). Hope this helps!
Greetings from another newbie ;)
Please try adding dimensions on your canvas
<canvas id="mycanvas" style:"height:400px; width:400px"></canvas>
or CSS style
<style>
#mycanvas {
height:400px;
width:400px;
}
</style>
canvas "'" also has syntax error.
because you have an error in your html
<canvas id="mycanvas'></canvas>
your canvas id begins with " and ends with '
change it to
<canvas id="mycanvas"></canvas>
and it should be fixed
Related
I'm trying to load the image on canvas but it's not working:(
I checked functions and variables much time but I couldn't find any errors.
Help me to find the reasons why it can't be loaded.
When I run it on the tomcat server, only the canvas with aliceblue color is shown.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Print image and text</title>
<script>
function drawPicture(ctx) {
var img = new Image();
img.addEventListener('load', function() {
ctx.drawImage(img, 20, 20, 100, 100);
ctx.font = "50px forte";
ctx.strokeStyle="blue";
ctx.fillStyle = "violet";
ctx.strokeText("Spongebob", 20, 100);
ctx.fillText("Spongebob", 20, 100);
}, false);
img.src = "spongebob.png";
}
</script>
</head>
<body>
<h3>Print image and text</h3>
<hr>
<canvas id="myCanvas" width="300" height="130"
style="background-color:aliceblue"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
drawPicture(context);
</script>
</body>
</html>
Your code is fine, here is an example with a different image...
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="130"></canvas>
<script>
function drawPicture(ctx) {
var img = new Image();
img.addEventListener('load', function() {
ctx.drawImage(img, 20, 20, 100, 100);
ctx.font = "50px forte";
ctx.strokeStyle = "blue";
ctx.fillStyle = "violet";
ctx.strokeText("Spongebob", 20, 100);
ctx.fillText("Spongebob", 20, 100);
}, false);
img.src = "http://i.stack.imgur.com/UFBxY.png";
}
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
drawPicture(context);
</script>
</body>
</html>
Only thing could be that the image you are trying to load does not exist...
As #Kaiido mentioned in the comments you need to debug this, check in your browser developer tools see if the image is loading correctly.
You should see something like:
instead of image.addEventListener, try doing image.onload?
You can instead of using the load event in the image, try adding the image directly on the canvas.
function drawPicture(ctx) {
var img = new Image();
img.src = "spongebob.png";
ctx.drawImage(img, 20, 20, 100, 100);
ctx.font = "50px forte";
ctx.strokeStyle="blue";
ctx.fillStyle = "violet";
ctx.strokeText("Spongebob", 20, 100);
ctx.fillText("Spongebob", 20, 100);
}
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
drawPicture(context);
<h3>Print image and text</h3>
<hr>
<canvas id="myCanvas" width="300" height="130"
style="background-color:aliceblue"></canvas>
I have a simple canvas in which I'm drawing a rectangle using Rough.js library. The issue I'm having is Rough js randomizing the draw pattern so each time the rectangle method is called, it seems to shake/jitter inside requestAnimationFrame. I'm not too familiar with the library I'm wondering if anyone here has any experience to either set some constants to force the rectangle to be drawn the exact same way or disable randomisation altogether.
<html>
<head>
<script type='text/javascript' src="https://unpkg.com/roughjs#4.3.1/bundled/rough.js"></script>
</head>
<body>
<canvas id="canvas" width="480" height="640"></canvas>
</body>
<script>
window.addEventListener('DOMContentLoaded',event=>{
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext('2d');
let r = rough.canvas(canvas);
function draw(tick){
requestAnimationFrame(draw);
ctx.clearRect(0,0,480,640);
r.rectangle(50, 50, 80, 80, {
fill: 'rgba(255,0,200,0.2)',
fillStyle: 'solid' // solid fill
});
}
requestAnimationFrame(draw);
});
</script>
</html>
When you run the snippet you can see the jittering/shaking. That's what I wish to disable.
You'll want to use the RoughGenerator to create a rectangle instruction once and reuse it:
const canvas = document.querySelector("canvas")
const ctx = canvas.getContext("2d");
const r = rough.canvas(canvas);
// First we set up a rectangle
const rect = r.generator.rectangle(50, 50, 80, 80, {
fill: 'rgba(255,0,200,0.2)',
fillStyle: 'solid' // solid fill
});
(function draw(tick) {
requestAnimationFrame(draw);
ctx.clearRect(0, 0, 480, 640);
// Then we draw it as many times as we want
r.draw(rect);
})();
<script src="https://unpkg.com/roughjs#4.3.1/bundled/rough.js"></script>
<canvas></canvas>
I am trying to draw a ball in my html using javascript. The javascript is referenced by the HTML file since it is an external script. However, I only get a blank page in return. Can someone help please? Thanks!
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device=width,initial-scale=1.0">
<script type = "text/javascript" src="projectscripts.js"></script>
</head>
<body onload="ball.draw()">
<canvas id="canvas" width = "3000" height = "3000"></canvas>
</body>
</html>
In my javascript file:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var raf;
var ball = {
x: 600,
y: 300,
radius: 25,
color: 'blue',
draw: function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2, true);
ctx.closePath();
ctx.fillStyle = this.color;
ctx.fill();
}
};
Move the <script type = "text/javascript" src="projectscripts.js"></script> just before </body>.
The error comes, because the script is executed before the body is rendered, and because of that the variable canvas is null and everything that is using it "blows".
I recommend to always have the devtools open, so you can debug and see errors.
I am trying to save canvas on my local machine but nothing is working . please check below code .
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<canvas id="myCanvas" width="578" height="400"></canvas>
<img id="canvasImg" alt="Right click to save me!">
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 69, 50);
// draw cloud
context.beginPath();
context.moveTo(170, 80);
context.bezierCurveTo(130, 100, 130, 150, 230, 150);
context.bezierCurveTo(250, 180, 320, 180, 340, 150);
context.bezierCurveTo(420, 150, 420, 120, 390, 100);
context.bezierCurveTo(430, 40, 370, 30, 340, 50);
context.bezierCurveTo(320, 5, 250, 20, 250, 50);
context.bezierCurveTo(200, 5, 150, 20, 170, 80);
context.closePath();
context.lineWidth = 5;
context.fillStyle = '#8ED6FF';
context.fill();
context.strokeStyle = '#0000ff';
context.stroke();
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
var imageData = canvas.toDataURL();
</script>
</body>
</html>
in this example code i am draing some image and cloud and wish to save it as as image file ???
As Sacho mentioned, 'tainting a canvas stops it being saved. This is a security feature to stop data from third-party websites being captured.
One workaround is to serve up all static images from your own website. This can be done by having your server download the image on request from the third-party site and return the data stream (as if it was on your own domain). Then the browser has no complaints about tainting as it is effectively from your server.
I have no idea what your server-side technology is, so can't suggest a specific implementation, but you basically could generate requests like:
/imagerequest.php?url=http%3A%2F%2Fwww.html5canvastutorials.com%2Fdemos%2Fassets%2Fdarth-vader.jpg
Where the source URL is provided as a parameter and imagerequest.php (or aspx) etc is your server script.
Try send your imageData to server via XMLHTTPRequest or fetch. Something like this:
const canvas = document.getElementById('cvs');
const context = canvas.getContext('2d');
context.font = '26pt Arial';
context.fillText('Some example text!', 10, 40);
url = canvas.toDataURL();
fetch('/yoururl', { method: 'POST', body: new FormData(url)})
.then(res => console.log(res))
Maybe this link helps too
Can I use the canvas element as a css background?
This has been possible in WebKit since 2008, see here.
<html>
<head>
<style>
div { background: -webkit-canvas(squares); width:600px; height:600px; border:2px solid black }
</style>
<script type="application/x-javascript">
function draw(w, h) {
var ctx = document.getCSSCanvasContext("2d", "squares", w, h);
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50);
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect (30, 30, 55, 50);
}
</script>
</head>
<body onload="draw(300, 300)">
<div></div>
</body>
</html>
Currently, Firefox 4 contains a feature, which allows you to use any element (including canvas) as a CSS background, in this fashion:
<p id="myBackground1" style="background: darkorange; color: white; width: 300px; height: 40px;">
This element will be used as a background.
</p>
<p style="background: -moz-element(#myBackground1); padding: 20px 10px; font-weight: bold;">
This box uses #myBackground1 as its background!
</p>
See Mozilla hacks for specifics.
Yes!!!! You can put a canvas in CSS background.
var Canvas = document.createElement("canvas");
... do your canvas drawing....
$('body').css({'background-image':"url(" + Canvas.toDataURL("image/png")+ ")" });
I know this is a pretty old question but I felt like posting my answer for people who'd visit this page because this is the correct answer, in just one line of code, using the .toDataURL function. It works in every browser that supports canvas.
I think the closest you could get is to render into a canvas, call toDataUrl() on it to retrieve the contents as an image, and assignment that result to the desired element's background-image property. This will only give a static background, though. If you want to be able to further update the canvas, however, then you'll need to instead position the canvas behind another element, as Johan has already suggested.
I've been triying to achieve this same feature past weeks, the best solution I've found its the same proposed by bcat:
Render canvas (visible or hidden)
Get canvas image with "canvas.toDataURL"
Asign this image-data as background image for the element (I use MooTools)
The bad news, for static images works great, but with animation in Chrome sometimes "blinks", and in Firefox blinks-a-lot. Maybe someone knows a workaround to get rid of this "nasty blinking".
Best regards.
P:.
<!DOCTYPE html>
<html>
<head>
<title>Asign canvas to element background</title>
<script type="text/javascript" src="/js/mootools.1.2.4.js"></script>
<style type="text/css">
* {
outline:0;
padding:0;
margin:0;
border:0;
}
body {
color:#fff;
background:#242424;
}
</style>
<script>
window.addEvent('domready',function() {
//GET BODY
var mibodi = $('mibodi');
var viewportSize = mibodi.getSize();
//GET CANVAS
var micanvas = $('micanvas');
var ctx = micanvas.getContext('2d');
var playAnimation = true;
//GET DIV
var midiv = $('midiv');
//VARIABLES
var rotate_angle = 0;
var rotate_angle_inc = 0.05;
//FUNCIÓN DE INICIALIZACIÓN
function init(){
ctx.clearRect (0, 0, 512, 512); //CLEAR CANVAS
ctx.fillStyle = 'rgba(128,128,128,1)';
ctx.strokeStyle = 'rgba(255,255,255,1)';
if (playAnimation) {
setInterval(draw,100);//
}
} //INIT
//FUNCIÓN DE DIBUJADO
function draw() {
//CLEAR BACKGROUND
ctx.clearRect (0, 0, 512, 512);
//DRAW ROTATING RECTANGLE
ctx.save();
ctx.translate( micanvas.width / 2, micanvas.height / 2 );
ctx.rotate( rotate_angle );
ctx.fillRect(0, 0, 100, 100);
ctx.restore();
//GET CANVAS IMAGE
var dataURL = micanvas.toDataURL("image/png");
//SET IMAGE AS BACKGROUND OF THE ELEMENTS
midiv.setStyle('background-image', 'url(' + dataURL + ')');
mibodi.setStyle('background-image', 'url(' + dataURL + ')');
//ANGLE INCREMENT
rotate_angle = rotate_angle + rotate_angle_inc;
} //DRAW
//BEGIN TO DRAW
init();
});//domeady
</script>
</head>
<body id="mibodi" >
<canvas id="micanvas" width="512" height="512" style="float:left;" style="display:none;">
Este texto se muestra para los navegadores no compatibles con canvas.
<br>
Por favor, utiliza Firefox, Chrome, Safari u Opera.
</canvas>
<div id="midiv" style="width:512px;height:512px;background:#f00;float:left;">
Sample
</div>
</body>
</html>
Try -moz-element(#id) for CSS background in Firefox.
And -webkit-canvas(name) for CSS background in WebKit based browsers.
You can use CSS Paint API
.elem {
backgound: paint(squares);
}
See more details here:
Blog posts:
https://vitaliy-bobrov.github.io/blog/exploring-the-css-paint-api/
https://vitaliy-bobrov.github.io/blog/css-paint-in-action-bar-chart/
Demos: https://vitaliy-bobrov.github.io/css-paint-demos/
You can emulate this behavior quickly without the performance drop of toDataURL() using z-index (granted, it's a workaround, since CSS images 4 / CSS Houdini hasn't implemented "background: element(#mycanvas)" as of 2017))
Working JSFiddle here. I didn't write this, all credit goes to Derek Leung:
http://jsfiddle.net/DerekL/uw5XU/
Unable to comment so I will create my own answer for this.
This answer is based off of #livedo, #Eric Rowell, and #shabunc
http://jsfiddle.net/MDooley47/yj26psdb/
window.i = 0;
function draw(w, h) {
window.i+=5;
if (window.webkitURL != null) {
var ctx = document.getCSSCanvasContext("2d", "squares", 100, 100);
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, w, h);
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect (30, 30, w, h);
}
else {
var ctxmozc = document.getElementById("squares");
var ctxmoz = ctxmozc.getContext("2d");
ctxmoz.fillStyle = "rgb(200,0,0)";
ctxmoz.fillRect (10, 10, w, h);
ctxmoz.fillStyle = "rgba(0, 0, 200, 0.5)";
ctxmoz.fillRect (30, 30, w, h);
}
}
setInterval(function(){draw(window.i, window.i);}, 500);
div {
background: -webkit-canvas(squares);
background: -moz-element(#squares) repeat-x;
width:575px;
height:475px;
border:2px solid black
}
<body>
<div></div>
<canvas id="squares" name="squaresmoz" style="display: none;" ></canvas>
</body>