How to put a picture on Canvas - javascript

I have been trying to get an image to appear on my canvas that I have drawn shapes onto but I haven't been able to get it to work. There was a similar question on here but I tried doing it that way and it didn't work for me. I don't really care where on the canvas the picture appears as long as I can actually get it to. Also when I tried to get the image on the canvas, it turned the whole canvas yellow? I'm not sure why but the pedals on my flowers are yellow and I did nothing to change that part of my code.
window.onload = function() {
drawStar(100,100,5,30,15);
TruckParts();
Flower();
colorDrop();
Test1();
};
function drawStar(cx,cy,spikes,outerRadius,innerRadius){
// Get referene to canvas object
var canvas = document.getElementById("myCanvas");
// Get reference to canvas drawing context
var context = canvas.getContext("2d");
var rot=Math.PI/2*3;
var x=cx;
var y=cy;
var step=Math.PI/spikes;
context.beginPath();
context.moveTo(cx,cy-outerRadius)
for(i=0;i<spikes;i++){
x=cx+Math.cos(rot)*outerRadius;
y=cy+Math.sin(rot)*outerRadius;
context.lineTo(x,y)
rot+=step
x=cx+Math.cos(rot)*innerRadius;
y=cy+Math.sin(rot)*innerRadius;
context.lineTo(x,y)
rot+=step
}
context.lineTo(cx,cy-outerRadius);
context.closePath();
context.lineWidth=5;
context.strokeStyle='lightblue';
context.stroke();
context.fillStyle='grey';
context.fill();
}
function TruckParts(){
// Get referene to canvas object
var canvas = document.getElementById("myCanvas");
// Get reference to canvas drawing context
var context = canvas.getContext("2d");
// Draw truck body
context.beginPath();
context.moveTo(125, 450);
context.lineTo(200, 450);
context.lineTo(250, 500);
context.lineTo(290, 500);
context.lineTo(290, 550);
context.lineTo(25, 550);
context.lineTo(25, 500);
context.lineTo(250, 500);
context.lineTo(110, 550);
context.lineTo(200, 500);
context.lineTo(125, 500);
context.closePath();
context.strokeStyle = "darkred";
context.lineWidth = 1;
context.stroke();
context.fillStyle = "red";
context.fill();
//Draw truck tire1
context.beginPath();
context.arc(100,560,30,0,2*Math.PI);
context.strokeStyle = "white";
context.lineWidth = 1;
context.stroke();
context.fillStyle = "black";
context.fill();
//Draw truck tire 2
context.beginPath();
context.arc(230,560,30,0,2*Math.PI);
context.strokeStyle = "white";
context.lineWidth = 1;
context.stroke();
context.fillStyle = "black";
context.fill();
};
//Draw Flower
function Flower(){
// Get referene to canvas object
var canvas = document.getElementById("myCanvas");
// Get reference to canvas drawing context
var context = canvas.getContext("2d");
//stem
context.beginPath();
context.moveTo(449, 500);
context.lineTo(449, 590);
context.lineTo(453, 590);
context.closePath();
context.fillStyle = "green";
context.fill();
//top left pedal
context.beginPath();
context.arc(436,490,20,0,2*Math.PI);
context.strokeStyle = "pink";
context.lineWidth = 1;
context.stroke();
context.fillStyle = "yellow";
context.fill();
//bottom right pedal
context.beginPath();
context.arc(465,512,20,0,2*Math.PI);
context.strokeStyle = "pink";
context.lineWidth = 1;
context.stroke();
context.fillStyle = "yellow";
context.fill();
//top right pedal
context.beginPath();
context.arc(465,490,20,0,2*Math.PI);
context.strokeStyle = "pink";
context.lineWidth = 1;
context.stroke();
context.fillStyle = "yellow";
context.fill();
//bottom left pedal
context.beginPath();
context.arc(436,512,20,0,2*Math.PI);
context.strokeStyle = "pink";
context.lineWidth = 1;
context.stroke();
context.fillStyle = "yellow";
context.fill();
//center
context.beginPath();
context.arc(450,500,17,0,2*Math.PI);
context.strokeStyle = "yellow";
context.lineWidth = 1;
context.stroke();
context.fillStyle = "pink";
context.fill();
};
//colors array
let colors = [
{colorname: "Red", color: "red" },
{colorname: "Blue", color: "blue"},
{colorname: "Green", color: "green"},
{colorname: "Purple", color: "purple"},
{colorname: "Pink", color: "pink"},
];
function colorDrop () {
let locaRef = document.querySelector("#colorDrop");
let option1 = document.createElement("option");
option1.value = 0;
option1.text = colors[0].colorname;
let option2 = document.createElement("option");
option2.value = 1;
option2.text = colors[1].colorname;
let option3 = document.createElement("option");
option3.value = 2;
option3.text = colors[2].colorname;
let option4 = document.createElement("option");
option4.value = 3;
option4.text = colors[3].colorname;
let option5 = document.createElement("option");
option5.value = 4;
option5.text = colors[4].colorname;
locaRef.appendChild(option1);
locaRef.appendChild(option2);
locaRef.appendChild(option3);
locaRef.appendChild(option4);
locaRef.appendChild(option5);
}
function handleDropdown(){
//convert index to number
let index = document.getElementById("colorDrop").value;
let setColor = colors[index].color;
};
//similar function that does not work for me
function Test1() {
let context = document.getElementById('test1');
if (context.getContext) {
context = context.getContext('2d');
//Loading of the home test image - img1
let img1 = new Image();
//drawing of the test image - img1
img1.onload = function () {
//draw background image
context.drawImage(img1, 0, 0);
//draw a box over the top
context.fillStyle = "rgba(200, 0, 0, 0.5)";
context.fillRect(0, 0, 500, 500);
};
img1.src = "puppy.jpg";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel= 'stylesheet' href="p3.css">
<script src="p3.js"> </script>
<style>canvas { border: 1px solid black; }</style>
</header>
<body>
<canvas width= "1000" height= "600" id= "myCanvas">
</canvas>
</body>
</html>
<header>
</header>
<nav>
</nav>
<main>
Enter text:
<input type="text">
<button type= "button">Press Button</button>
<select id="colorDrop" onchange="handleDropdown()">
<option value="">Select a Color</option>
</select>
</main>
<footer>
</footer>
</body>
</html>

The following line in the Test1 function is preventing your code from working...
let context = document.getElementById('test1');
Needs to be changed of course to...
let context = document.getElementById('myCanvas');
When I make this change your code works, the image I specify for img1.src is displayed top-left of the canvas, and a filled rectangle of 50% alpha also appears.

Related

Line drawing in canvas with gradient

I'm looking for a solution to freehand draw a line with a gradient in canvas like this:
I already found this, but the gradient seems to be 'locked' on the background and is not following the line.
window.addEventListener('load', ()=>{
resize(); // Resizes the canvas once the window loads
document.addEventListener('mousedown', startPainting);
document.addEventListener('mouseup', stopPainting);
document.addEventListener('mousemove', sketch);
window.addEventListener('resize', resize);
});
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
function resize(){
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
}
let coord = {x:0 , y:0};
let paint = false;
function getPosition(event){
coord.x = event.clientX - canvas.offsetLeft;
coord.y = event.clientY - canvas.offsetTop;
}
function startPainting(event){
paint = true;
getPosition(event);
}
function stopPainting(){
paint = false;
}
function sketch(event){
if (!paint) return;
ctx.beginPath();
ctx.lineWidth = 5;
ctx.lineCap = 'round';
var gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0.00, 'grey');
gradient.addColorStop(1 / 2, 'white');
gradient.addColorStop(1.00, 'grey');
ctx.strokeStyle = gradient;
ctx.moveTo(coord.x, coord.y);
getPosition(event);
ctx.lineTo(coord.x , coord.y);
ctx.stroke();
}
Can somebody help me please?
I found a way to do it:
var context = canvas.getContext("2d");
context.strokeStyle = '#000000';
context.fillStyle = '#000000';
context.beginPath();
context.moveTo(10, 10);
context.lineTo(50, 10);
context.lineWidth = 2;
context.stroke();
context.beginPath();
context.lineWidth = 15;
context.moveTo(10, 30);
context.lineTo(50, 30);
context.stroke();
context.beginPath();
context.moveTo(10, 50);
context.lineTo(50, 50);
context.lineWidth = 2;
context.stroke();
Where I reconstructed the gradient with multiple lines and a blur on those lines.

How to create html5 canvas for bordered boxes?

I am trying to create below canvas.
Image
my code is below. but I am having trouble to make the canvas look the like the screenshot above. can anyone help me then?
thanks though
<html>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
var canvas;
var canvasContext;
window.onload = function() {
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
canvasContext.fillStyle = 'blue';
canvasContext.fillRect(0,0,canvas.width,canvas.height);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(355,350,120,90);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(190,350,120,90);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(520,350,120,90);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(355,200,120,90);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(190,200,120,90);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(520,200,120,90);
}
</script>
</html>
.fillRect creates a filled region of color. However, .rect creates a "shape" that you can then use the .fill() and .stroke() methods upon.
In the below example if converted creation into a loop for brevity
var canvas;
var canvasContext;
window.onload = function() {
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
canvasContext.fillStyle = 'blue';
canvasContext.fillRect(0,0,canvas.width,canvas.height);
var height = 90;
var width = 120;
var leftOffset = 190;
var topOffset = 200;
for(var x = 0; x < 6; x++){
canvasContext.beginPath();
canvasContext.rect(leftOffset,topOffset,width,height);
canvasContext.fillStyle = 'grey';
canvasContext.fill();
canvasContext.lineWidth = 4;
canvasContext.strokeStyle = 'lightblue';
canvasContext.stroke();
leftOffset += 165;
if(x === 2){
leftOffset = 190;
topOffset = 350;
}
}
}
JSFIDDLE
This tutorial on HTML5 Canvas rectangles is very handy
To add the text, you would append the following after (or before) the rect creating loop
canvasContext.beginPath();
canvasContext.font = '20pt Arial';
canvasContext.textAlign = 'center';
canvasContext.fillStyle = 'white';
canvasContext.shadowColor = 'black';
canvasContext.shadowOffsetX = 4;
canvasContext.shadowOffsetY = 4;
canvasContext.fillText('CHOOSE A SCENE TO COLOR', canvas.width/2,55);
UPDATED FIDDLE
Tutorials for text align, text shadow, and text.
Try something like this, use a function to draw a rectangle with exactly the border you want. The trick is to use .rect instead of fillRect so that you can use .stroke() immediately after.
<html>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
function draw_bordered_rect(context, x, y, w, h) {
context.rect(x, y, w, h);
context.fillStyle = "grey";
context.fill();
context.lineWidth = 3;
context.strokeStyle = "lightblue";
context.stroke();
}
window.onload = function() {
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
canvasContext.fillStyle = 'blue';
canvasContext.fillRect(0, 0, canvas.width, canvas.height);
canvasContext.font = '25pt Arial';
canvasContext.textAlign = 'center';
//drop shadow 2px to the left and 2px below the white text
canvasContext.fillStyle = "black";
canvasContext.fillText('CHOOSE A SCENE TO COLOR', canvas.width/2-2, 82);
//actual text ontop of the drop shadow text
canvasContext.fillStyle = 'white';
canvasContext.fillText('CHOOSE A SCENE TO COLOR', canvas.width/2, 80);
draw_bordered_rect(canvasContext, 355, 350, 120, 90);
draw_bordered_rect(canvasContext, 190, 350, 120, 90);
draw_bordered_rect(canvasContext, 520, 350, 120, 90);
draw_bordered_rect(canvasContext, 355, 200, 120, 90);
draw_bordered_rect(canvasContext, 190, 200, 120, 90);
draw_bordered_rect(canvasContext, 520, 200, 120, 90);
}
</script>
</html>
Looks like:
I have some code to design canvas box in HTML5. I think you should try this one, I hope it will help you to design your canvas box. I think you should use JavaScript mehtod context.fillRect as i am giving you Js Fidler Lind here
HTML Code
<canvas id="myCanvas" width="500" height="400">
<!-- Insert fallback content here -->
</canvas>
JavaScript Code
var canvas = $("#myCanvas");
var context = canvas.get(0).getContext("2d");
// Set rectangle and corner values
var rectX = 50;
var rectY = 50;
var rectWidth = 100;
var rectHeight = 100;
var cornerRadius = 20;
// Reference rectangle without rounding, for size comparison
context.fillRect(200, 50, rectWidth, rectHeight);
// Set faux rounded corners
context.lineJoin = "round";
context.lineWidth = cornerRadius;
// Change origin and dimensions to match true size (a stroke makes the shape a bit larger)
context.strokeRect(rectX+(cornerRadius/2), rectY+(cornerRadius/2), rectWidth-cornerRadius, rectHeight-cornerRadius);
context.fillRect(rectX+(cornerRadius/2), rectY+(cornerRadius/2), rectWidth-cornerRadius, rectHeight-cornerRadius);
// You can do the same thing with paths, like this triangle
// Remember that a stroke will make the shape a bit larger so you'll need to fiddle with the
// coordinates to get the correct dimensions.
context.beginPath();
context.moveTo(400, 60);
context.lineTo(440, 140);
context.lineTo(360, 140);
context.closePath();
context.stroke();
context.fill();
This javascript code will design canvas box just like below g]iven image

Drawing Shadow of an object in Canvas

I want to draw one circle and a character with shadow on a canvas in a HTML page while loading the page and recreate the image on a button click. I am using this code:
window.onload = function() {
draw();
};
function draw(){
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, c.width, c.height);
var width = c.width;
var height = c.height;
//DRAW A CIRCLE
var centerX = Math.floor((Math.random() * width));
var centerY = Math.floor((Math.random() * height));
var radius = Math.floor(Math.random() * 50);
var color = '#f11';
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
//DRAW A CHARACTER WITH SHADOW
var c = "S";
ctx.font = "300% Verdana";
ctx.shadowBlur = 20;
ctx.shadowColor = "black";
ctx.shadowOffsetX = 20;
ctx.shadowOffsetY = 20;
ctx.fillStyle = "#111";
ctx.fillText(c, 10, 90);
}
In HTML I am calling draw function onclick() event of a button named Refresh.
For the first time it is giving desired output by drawing one circle and a character with shadow. As I click on the Refresh button it is drawing both the objects with shadow. I dont want to draw shadow of the circle. Can anyone please tell me the mistake I'm doing here.
You may want to use the CanvasRenderingContext2D.save() method :
window.onload = function() {
draw();
};
document.getElementById("canvas").addEventListener('click', draw);
function draw(){
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, c.width, c.height);
var width = c.width;
var height = c.height;
//DRAW A CIRCLE
var centerX = Math.floor((Math.random() * width));
var centerY = Math.floor((Math.random() * height));
var radius = Math.floor(Math.random() * 50);
var color = '#f11';
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
//DRAW A CHARACTER WITH SHADOW
//save the actual context
ctx.save();
var c = "S";
ctx.font = "300% Verdana";
ctx.shadowBlur = 20;
ctx.shadowColor = "black";
ctx.shadowOffsetX = 20;
ctx.shadowOffsetY = 20;
ctx.fillStyle = "#111";
ctx.fillText(c, 10, 90);
//restore it
ctx.restore();
}
canvas{border:1px solid;}
<canvas id="canvas" width="400" height="200"></canvas>

Trying to make every other house's door green

What my task is, is to draw a house then use a loop (at the bottom) to fill the canvas with the houses instead of manually placing each one.
Well I'm trying to work how to make every other house's door green. I've been trying to hack away at code for awhile now but I cannot figure it out.
I know all my house pieces should be in functions and what not but that is a later task for the work I am doing! Here's my code:
//Check to see if the browser supports
//the addEventListener function
if(window.addEventListener)
{
window.addEventListener
(
'load', //this is the load event
onLoad, //this is the evemnt handler we going to write
false //useCapture boolen value
);
}
//the window load event handler
function onLoad()
{
var canvas;
var context;
//this function will intialise our variables
function initialise()
{
// Fune the canvas element using its id attribute.
canvas = document.getElementById('canvas');
//if it couldn't be found
if (!canvas)
{
//make a message bok appear with an error message
alert('Error: i cannot find this "canvas" of which you speak. Please re-evaluate your life choices.');
return;
}
//check if there is any getContext function
if(!canvas.getContext)
{
alert('Error no cavnas.getContext could be found');
return;
}
//get the 2D canvas context.
context = canvas.getContext('2d');
if(!context)
{
alert('Error failed to getCOntext');
return;
}
canvas.addEventListener("mousedown", getPosition, false);
}
// this is a little help tool for me as i'm awful at working out co-ordinates
function getPosition(e)
{
var x = e.x;
var y = e.y;
x -=canvas.offsetLeft;
y -=canvas.offsetTop;
alert("x:" +x+ "y:"+y);
}
//this function will draw on the canvas for me!
function draw()
{
context.fillStyle = 'grey';
context.fillRect(0, 0, canvas.width, canvas.height);
}
// pX and pY are the parameters are going to be used so that the inside of the house body becomes the drawing canvas.
function drawHouse(pX ,pY)
{
//body
context.beginPath();
context.fillStyle = '#ffffff';
context.strokeStyle = "black";
context.lineWidth = "5";
context.rect(pX,pY, 160,110);
context.closePath();
context.fill();
context.stroke();
//roof
context.beginPath();
context.fillStyle = "red";
context.moveTo(pX,pY-1);;
context.lineTo(pX+80, pY-95);
context.lineTo(pX+160, pY-1);
context.closePath();
context.fill();
context.stroke();
//door
context.beginPath();
context.fillStyle = "green";
context.fillSStyle = "red";
context.strokeStyle = "black";
context.rect(pX+55,pY+30, 50, 80);
context.fill();
context.stroke();
//handle
var radius = 5;
context.beginPath();
context.arc(pX+93, pY+75, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'purple';
context.fill();
context.lineWidth = 3;
context.strokeStyle = 'black';
context.stroke();
//window Left
context.beginPath();
context.fillStyle = 'blue';
context.strokeStyle = "black";
context.rect(pX+12,pY+30, 30, 60);
context.fill();
context.stroke();
//window Filler left vertically
context.beginPath();
context.moveTo(pX+26.5,pY+30);
context.lineTo(pX+26.5, pY+90);
context.fill();
context.stroke();
//Window filler left horizontally
context.beginPath();
context.moveTo(pX+41, pY+60);
context.lineTo(pX+11,pY+60);
context.fill();
context.stroke();
//Window Right
context.beginPath();
context.fillStyle = 'blue';
context.strokeStyle = "black";
context.rect(pX+117,pY+30, 30, 60);
context.fill();
context.stroke();
//window filler right vertically
context.beginPath();
context.moveTo(pX+131.5,pY+30);
context.lineTo(pX+131.5, pY+90);
context.fill();
context.stroke();
//window Filler right horizontally
context.beginPath();
context.moveTo(pX+147, pY+60);
context.lineTo(pX+117,pY+60);
context.fill();
context.stroke();
}
initialise();
draw();
for(var i=0; i < 5; i++)
{
var pX=0+160*i;
for(var b=0; b < 5; b++)
{
var pY=100+210*b;
drawHouse(pX,pY);
}
}
}
Add a parameter to drawHouse:
function drawHouse(pX, pY, drawGreen) {
// ...
if (drawGreen)
context.fillStyle = "green";
else
context.fillSStyle = "red";
// ...
}
And then, pass it accordingly. For example:
// before your loop
var paintGreen = false;
// In the inner for
var pY=100+210*b;
drawHouse(pX,pY,paintGreen);
paintGreen = !paintGreen; // alternate

Is there a way to tile a background image over a canvas path?

For example, I have a canvas in a page with some kind of a path. It is created by javascript this way:
var context = $('#some_canvas').getContext('2d');
context.beginPath();
context.lineWidth = 5;
context.strokeStyle = '#000000';
context.moveTo(0, 0);
context.lineTo(100, 100);
context.stroke();
Is there a way to make the path that appears after this command to have some tiled background image?
I believe you're looking for the createPattern() method:
var pattern = new Image;
pattern.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAARCAIAAABbzbuTAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAZtJREFUeNqMUs+rAVEUvjNG2MhClOUsppSEjbWFpOwtMIv5B2ZhZqkkZKkpe+XPYKtsbSxsZIGaQpgi4r3Pu5p3eV45dW/nnPt959zzg5RKpU6n8/WxkHq9LghCs9n8lICjKAohpFwuf0LgcCzLSqfTo9FIVVVd10He7XbX6/V8Pu/3e47jcB+Px0AgkEqlCOXNZjNJkgB1/wg+6XA4ACXPomkasXM1Gg3yj4AZi8WAHgwGgu1dLpcvOKRKJBLZbDaTyYDgdDrvXjtDLpd7yT6dTv8WzdNnaPP53A6Mezgc+v3+N/+jvO12GwwGqQfFYJRQksnker1+MwfIZDLxeDwA+Xy+xWIBT6VSgYk+Hg4HlvAoerVaodNQ8vl8KBSCUqvVAG2326g4EolsNhuYGNQjQ6/XAwh9GI/HbDxZltn/o2OPDBgctaPRKIsQRZEqWJxisXg3aaRCoQBvv99nw59Op3A4DH+1Wu12u09FYwh4w/6wBGwUOhuPx6FfLpfb7fZbtGEYpmnyPM/+x+v1tlotl8sFHdtFnd8CDACAg6Y2weEZQQAAAABJRU5ErkJggg==";
pattern.onload = function () {
var context = $('#some_canvas').getContext('2d');
context.beginPath();
context.lineWidth = 16;
context.strokeStyle = context.createPattern(pattern, 'repeat');
context.moveTo(0, 0);
context.lineTo(150, 150);
context.stroke();
};

Categories