How do you get code like this to run in JsFiddle.net? - javascript

I'm looking at sample code on how to draw shapes using only JavaScript.
I'm trying to test this sample code in JSFiddle.net, and while hitting 'Run' doesn't produce any errors, the result is completely blank.
Does anyone know how to make something actually appear on the screen in JsFiddle.net?
draw = function() {
//sky
background(172, 238, 247);
//ground
fill(95, 156, 83);
rect(0, 350, 400, 50);
};
draw();
Link to non-working Fiddle:
https://jsfiddle.net/skdopL1b/

So the way javascript works with HTML to draw things is through the Canvas API. First you have to contextualization and establish interactions between JS code and <canvas> element. This is done with built in function and then a little bit of code to make it short-hand.
<html>
<canvas id="canvas" width="500" height="400"></canvas>
<script>
const c = document.getElementById("canvas"); //Grab canvas element to use as object
const ctx = c.getContext('2d'); //Function that enable the 2d functions of Canvas API
ctx.fillRect(0,0,10,10) //Example of ctx function
<script>
</html>
From the JS Fiddle you gave us, It looks like you probably copied functions from a video that pre-established these function as they are not normal canvas function but custom functions. I can show you example of how to write one of these custom functions
function background(red,green,blue) {
ctx.fillStyle = 'rgb('+red+','+green+','+blue+')';;
ctx.fillRect(0,0,c.width,c.height); //Makes a rectangle the size of the canvas
}
background(172,238,247); //Creates a canvas sized rectangle with rgb(172,238,247)
You will have to either find his function declarations or write your own (or just use the raw canvas functions) to work with the javascript this way. You also need to define a canvas element with an ID. Lucky for you Im working on making a JSFiddle that works for you since you seem fairly new to this whole HTML5/JS thing.
-------EDIT-------
Heres your fiddle link friend, I included comments to help you understand everything https://jsfiddle.net/xwqg1cez/2/

Related

createjs removed all existing info on canvas?

I am trying to verify that this happens no matter what, and there's no way to bypass it. It seems pretty silly to me that createjs uses this architecture. But I noticed that creating a stage from an existing canvas element removes all shapes, writings, etc from the canvas? Code is below:
html:
<canvas id="canvas" width="800" height="400"></canvas>
js:
var canv = document.getElementById("canvas");
var stage = new createjs.Stage(canv);
var ctx = canv.getContext('2d');
ctx.beginPath();
ctx.arc(50,50,10,0,2*Math.PI);
ctx.stroke();
createjs.Ticker.addEventListener("tick", tick);//circle created is overwritten here!!!?! Why createjs!?
//stage.update();
createjs.MotionGuidePlugin.install();
var shape1 = new createjs.Shape();
shape1.graphics.f("#000000").dc(0,0,10);
var path1 = new createjs.Shape();
path1.graphics.beginStroke("#ff0000").mt(0,0).qt(50,100,100,0);
stage.addChild(path1, shape1);
createjs.Tween.get(shape1).to({guide:{ path:[0,0, 50,100, 100,0] }},2000, createjs.Ease.cubicInOut);
function tick(event) {
stage.update();
}
Is this something that cannot be bypassed? It seems silly to me that createjs wouldn't just actually use the existing element unerased. If not, what is the point in passing in an element in the first place, why doesn't it just create a canvas element, and give you the ID? Anyways, if this is how it's going to be, unfortunately, I am going to have to go somewhere else. Sad, because createjs seemed pretty useful.
CreateJS uses a retained graphics mode, that is, it stores the state and redraws it each time. This is because the canvas is basically a big Bitmap with drawing commands – clearing the stage is the only way to remove the previous state.
But good news! There are lots of ways to get around these limitations if you want to blend CreateJS content with other content, or even make additive drawing effects.
The first is easy, which is setting autoClear. This will prevent the clear, and just draw the new contents over the old one.
stage.autoClear = false;
The second is a bit tougher, but great for instances where you want to mix CreateJS content with other libraries or effects. You can basically use the other canvas as the source to a Bitmap you include in CreateJS:
// Create a child for CreateJS referencing the other canvas
var bmp = new createjs.Bitmap(otherCanvas);
// Add it at the bottom (or top or wherever) in your new CreateJS canvas
stage.addChildAt(bmp, 0);
This is a great approach because it lets you put your content wherever you want, edit it separately, etc.
If you have a different case this doesn't cover, let me know and I can try to make a recommendation!
Cheers.

JavaScript file with query string to dynamically generate canvas as a png image in img src

I have a JavaScript that renders a drawing on canvas taking into account three given variables. I would like it to function as an image that can be referred to externally, i.e. by writing <img src="canvas.js?a=abc&b=def&c=ghi"> within any html file it should generate a PNG image there. Any suggestions?
I see that you're using PHP syntax in your question. You can't pass variables to JavaScript as you would in PHP. Instead, you should create a function and call it, passing variables that way.
Here's an example that should help you:
HTML
<!-- your generated image will be displayed here -->
<canvas id="your-canvas" width="800" height="600"></canvas>
<!-- include canvas.js -->
<script src="canvas.js"></script>
<script>
// call the function that is defined in canvas.js
drawImage("abc","def","ghi");
</script>
canvas.js
// select the canvas element in your page
let canvas = document.getElementById("your-canvas");
let ctx = canvas.getContext("2d");
// define a function that draws inside your selected canvas element
function drawImage (a, b, c) {
ctx.font = "30px Arial";
ctx.fillText(a + b + c, 10, 50);
}
Edit: I have also noticed that you're trying to output canvas.js to an img element. Unfortunately, that is impossible. Instead you'll need to use a canvas element, like I showed in my example (the output will still be an image).

I want to write Javascript for an HTML5 canvas, but I don't know how to set the canvas up

Up until now, I have only used Javascript in an environment that doesn't require any HTML, like the one on Khan Academy here. However, now I'm using sublime text, and I realize that I can't just write ellipse() and have it show up on the screen. Now I need the element. However, according to w3schools, now, for a circle to show up, I need to do this:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
Ugh. I really don't want to have to write "ctx" before every single line of code I make, or learn a bunch of new commands like "beginPath" and "lineTo". Is there a way I can create the canvas, and still make a program without all this messy stuff? Or, if that's not possible, could someone point me to a library that can? Thanks so much!
While this approach still doesn't free you from the responsibility of knowing your way around the canvas element, you can make use of the with keyword to avoid continually typing ctx - the approach is not one I use and as per the MDN page Statements and declarations>with you can run into problems with ambiguity.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
with (ctx)
{
beginPath();
arc(95,50,40,0,2*Math.PI);
stroke();
}
<canvas id='myCanvas'></canvas>
Not really sure what the question is. But from what I understood you need to learn how to add a canvas to a HTML file and link your JS to the same. If so, here's how to do it.
HTML as below
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width">
<title>Your Canvas Application</title>
<!-- link your js file as below -->
<script src = "path/to/yourjsfile.js">
</head>
<body>
<canvas id="myCanvas" width="500" height="500"></canvas>
</body>
JS file (yourjsfile.js) as below
window.onload = function () {
var canvas = document.getElementById("myCanvas");
var c = canvas.getContext("2d");
c.beginPath();
c.arc(95,50,40,0,2*Math.PI);
c.stroke();
};
You really can not entirely get rid of 'ctx', but instead you can shorten it for something like 'c'. Rather than looking for libraries, I recommend you learn the basics correct first. Then you can go ahead and explore the other options.

How to remove a drawn arch from canvas

I have been trying to print arc in the html page. How can i remove the already drawn arch from the page?. i have written the below code.
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="1200" height="1000"
style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
/*ctx.beginPath();
ctx.arc(600,500,20, 0.5*Math.PI,2*Math.PI);
ctx.stroke();
ctx.beginPath();
ctx.arc(600,500,40, 0.5*Math.PI,2*Math.PI);
ctx.stroke();
*/
var radius=20;
for (i=0; i<10; i++)
{
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(600,500,radius, 0.5*Math.PI, 2*Math.PI);
ctx.stroke();
radius= radius+30;
}
</script>
</body>
</html>
How can i achieve this?.
Call clearRect method:
ctx.clearRect(0, 0, 1200, 1000)
The four arguments are:
axis-X of left top corner of the area to wipe
axis-Y of left top corner of the area to wipe
width of the area to wipe
height of the area to wipe
So with this method, you could wipe either the whole canvas or just a certain part of it.
If you want to remove the whole previously drawn image please take a look at the other anwers. In the comments OP made it clear that this is not what he was trying to achieve. So instead I will answer the intended question:
How do I un-stroke a path?
A bitmap is not a vector graphic. You cannot simply remove or modify things you've drawn previously. By drawing on a canvas you modify the pixel color values of its image data. If you need to undo things you have to maintain a separate data structure with the relevant data yourself.
For example you could create a copy of the image data before drawing something. Then you could return to this snapshot afterwards. HTMLCanvasElement#toDataURL returns the complete image as an url which you can use as the src of an image. Later you can draw this image on the canvas to revert all subsequent changes. HTMLCanvasElement#toBlob does about the same but it returns a blob. This might consume less memory but it's a little more inconvenient to use. The most convenient method is CanvasRenderingContext2D#getImageData. You can even use it to copy only a small part of the image. This is useful if you have a big canvas but only modify pixels in a small region.
Another way to make modifications undoable is by maintaining a detailed list of your steps. For example whenever you draw an arc you store the exact parameters as one entry in the list. steps.push({type: 'stroke', style: 'rgb(0,0,0)', shapes: [{type: 'arc', x: 600, y: 500, radius: radius, from: 0.5 * Math.PI, to: 2 * Math.PI}]}) You can remove, rearrange or modify the elements in this list any way you like and have all necessary information to draw the resulting image from scratch. Basically you've implemented just another vector graphic library.

Shape rollover in JavaScript

I have drawn 2 images in canvas using javascript (lineTo, moveTo, rect etc.), and I want to manipulate these images in a rollover kinda way. I know I'm supposed to write functions like "onmouseover" and "onmouseaway", thing is I don't know how I can manipulate the two shapes I already have in the canvas given that I don't have their sources... I tried googling but it got a bit confusing.
alert: i'm beginner in JS
http://jsfiddle.net/aertop9416/J7Brj/embedded/result/
.js file
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
function drawTriangle(){
context.beginPath();
context.moveTo(225,275);
context.lineTo(25,25);
context.lineTo(0,275);
context.fill();
// context.fillStyle = 'rgb(200, 95, 124)';
};
function drawRect(){
context.fillRect(300,25,100,100);
// context.clearRect(245,245,60,60);
// context.strokeRect(250,250,50,50);
context.fillStyle = 'rgb(120, 195, 124)';
};
If you're not using a library such as EasleJS for interactivity (http://www.ajohnstone.com/test/hackday/CreateJS-EaselJS-b262a85/tutorials/Mouse%20Interaction/), It's going to be a bit tricky, since canvas uses immediate render mode you need to retain the state of your objects. Use the mouse interaction event listeners to trigger an animation loop (hopefully using requestAnimationFrame for performance see: http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/). I hope this gets you going in the right direction.

Categories