-3

I am new to jQuery can anyone tell how to do this?

I am doing this in between html code

<script>
var Canvas_width=400;
var Canvas_height=300;
var CanvasElement =$("<canvas width='" + Canvas_width + "'height='" + Canvas_height + "'></canvas>");
var canvas=CanvasElement.get(0).getContext("2d");

CanvasElement.appendTo('body');
canvas.fillStyle = "#000000";
canvas.fill();
</script>
3

2 Answers 2

0

You just need to create a rectangle the same size as your canvas before filling it:

canvas.rect(0, 0, Canvas_width, Canvas_height);

Demo

var Canvas_width = 400;
var Canvas_height = 300;
var CanvasElement = $("<canvas width='" + Canvas_width + "' height='" + Canvas_height + "'></canvas>");
var canvas = CanvasElement.get(0).getContext("2d");

CanvasElement.appendTo('body');
canvas.rect(0, 0, Canvas_width, Canvas_height); // <======= HERE
canvas.fillStyle = "#000000";
canvas.fill();
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

3 Comments

Can you please tell me what this line does:::: var CanvasElement = $("<canvas width='" + Canvas_width + "' height='" + Canvas_height + "'></canvas>");
@ManishKumar It's using jQuery to create a <canvas></canvas> HTML element (DOM element), of the width and height defined above.
@blex.Sir.I want to set border to my canvas using canvas.style.border = "red 1px solid"; . It's not working here in my case on browser's console it is printing "Uncaught TypeError: Cannot set property 'border' of undefined at some line number".
0

Here's how you should do it. Don't add the canvas context, add the element itself

var Canvas_width=400;
var Canvas_height=300;
var CanvasElement = $("<canvas width='" + Canvas_width + "'height='" + Canvas_height + "'></canvas>");
// Add the canvas element, not the context: CanvasElement[0].getContext('2d')
document.body.appendChild(CanvasElement[0]);

// Now create the canvas context, this is what you need to draw something
var canvasContext=CanvasElement[0].getContext("2d");
// call beginPath() before drawing on the canvas
canvasContext.beginPath();
// Select the rectangle inside your canvas in which you want to draw something
canvasContext.rect(0, 0, Canvas_width, Canvas_height);
canvasContext.fillStyle = "#000000";
canvasContext.fill();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.