<!DOCTYPE html>
<html>
<head>
<style>
#container {
width: 320px;
height: 480px;
border: 1px solid red;
}
</style>
</head>
<body>
<div style="position: relative;" id="container">
<canvas id="myCanvas" width="320" height="480"
style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
<canvas id="plane" width="320" height="480"
style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
<canvas id="canvas2" width="100" height="100"
style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
</div>
<img id="scream" src="http://4.bp.blogspot.com/-BrJHwoqM2qg/Uq94Il8t-1I/AAAAAAAAD7s/vyFLZUgMkdA/s1600/Plane.png" alt="The Scream" width="0" height="0">
<script>
var c=document.getElementById("myCanvas");
var c2=document.getElementById("canvas2");
var c3=document.getElementById("plane");
var plane;
var ground;
var score1 = "1"
var score = score1;
var increase = 6;
var delay = 40;
var scorez;
start();
function start(){
backgrounds();
planeDraw();
var scorez = setInterval(scoring, delay);
}
function backgrounds(){
var ctx=c.getContext("2d");
var my_gradient=ctx.createLinearGradient(0,0,0, 280);
my_gradient.addColorStop(0,"white");
my_gradient.addColorStop(1,"blue");
ctx.fillStyle=my_gradient;
ctx.fillRect(0,0,320,480);
ground = c.getContext("2d");
ctx.fillStyle="black";
ctx.fillRect(0,450 , 320 ,30);
}
function scoring(){
scores();
score2();
}
function scores(){
score -= 3-(3+increase);
}
function score2(){
//var canvas = document.getElementById('canvas2');
var context = c2.getContext('2d');
context.clearRect(0, 0, c2.width, c2.height);
var w = c2.width;
c2.width = 1;
c2.width = w;
var text=c2.getContext("2d");
text.font="20px Georgia";
text.fillText(score ,15,20);
}
function hit(){
}
function loes(){
clearInterval(scorez);
}
function planeDraw(){
plane = c3.getContext('2d');
var img = new Image();
img.src = "http://4.bp.blogspot.com/-BrJHwoqM2qg/Uq94Il8t-1I/AAAAAAAAD7s/vyFLZUgMkdA/s1600/Plane.png"; //transparent png
plane.drawImage(img, 0, 0, 320, 100);
}
</script>
<!--
http://4.bp.blogspot.com/-BrJHwoqM2qg/Uq94Il8t-1I/AAAAAAAAD7s/vyFLZUgMkdA/s1600/Plane.png
--!>
</body>
</html>
All the code seems to be working fine, the only issue I am finding is the image of the plane is not printing. Could some one please tell me what I am doing wrong. Thank you.
When I changed the planeDraw function to create a rectangle it worked perfectly. As well as this the code worked in JSFiddle, when it was isolated.
You are drawing the image before it has loaded.
Load the plane image once, and draw it after its onload event has fired.
If you can, consider embedding the image as a data: URL, as this will remove the need for waiting for the image to load, however keep in mind that it makes your code bigger!
You have to wait for the image to load before drawing it.
Try:
img.onload = function()
{
plane.drawImage(img, 0, 0, 320, 100);
};
img.src = "http://4.bp.blogspot.com/-BrJHwoqM2qg/Uq94Il8t-1I/AAAAAAAAD7s/vyFLZUgMkdA/s1600/Plane.png"; //transparent png
It's best to define the onload function before setting the src attribute - depending on the browser, if the image file is in your cache, the onload event may fire as soon as the src is set (before you have a chance to define onload).
Related
I am writing a code that takes in an image and pastes it into an HTML canvas. The code works when I declare my <img> in the HTML file, but this does not allow the user to input a new file.
Here is the html structure (the program works if the tag line is put back in:
<style type='text/css'>
canvas{
border: 10px solid black;
}
</style>
</head>
<body>
<canvas id='balls'>
</canvas>
<canvas id='hide' style:'border: 10px solid black;'>
<!-- <img id="taco" width="300" height="300" src="prime.png"> -->
</canvas>
<div>
<input id='url' placeholder="image url">
<button id='submit'>Submit</button>
</div>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please upgrade your browser to improve your experience.</p>
<![endif]-->
<script src="client.js" async defer></script>
</body>
</html>
Here is the portion of JS code I am working on:
$(document).ready(onReady);
var canvas = document.querySelector('canvas');
canvas.width = 300;
canvas.height= 300;
let bounced = false;
let newPic = `id="taco" width="300" height="300" src="prime.png"`
function onReady(){
$('#submit').on('click', updateImage)
$('#hide').empty()
$('#hide').append(`<img ${newPic}>`)
makeCanvas();
setup();
animate();
}
function updateImage() {
newPic= `id="taco" width="300" height="300" src="${$('#url').val()}" alt="prime.png"`
//console.log(newPic)
$('#hide').empty()
$('#hide').append(`<img ${newPic}>`)
makeCanvas();
setup();
animate();
}
let c, can, ctx, img
function makeCanvas(){
c = canvas.getContext('2d');
can=document.getElementById("hide");
console.log(can)
can.width = 300;
can.height = 300;
ctx=can.getContext("2d");
img=document.getElementById("taco");
ctx.drawImage(img,10,10);
console.log(img)
console.log(ctx.drawImage(img,10,10))
}
My console.log statements for img are identical when the code in the HTML file is placed back in.
When you're setting up your canvas, your image isn't loaded at all. So your
ctx.drawImage(img,10,10);
call just draws... an unloaded image... an empty set of bytes... Nothing.
So you should first load your image. After that, drawing stuff will easily be done. Here's a little code example:
var canv, ctx, img;
function setup() {
//Setting up canvas
//Fetching Context
ctx = canv.getContext("2d");
//Now drawing our image
ctx.drawImage(img,10,10);
}
img = new Image();
img.onload = setup; //We'll setup the canvas after the image is fully loaded
img.src = "your/path/or/variable/pointing/to/your/image.ext";
Hope it helps!
I'm trying to convert svgs to png's in javascript by way of canvas elements (inspired by "https://bl.ocks.org/biovisualize/8187844"), but I'm having issues rendering fonts which I'm linking to.
See the fiddle: https://jsfiddle.net/2chtz7rx/1/
Html:
<link href="https://fonts.googleapis.com/css?family=Creepster:400,400" rel='stylesheet' type='text/css'>
<svg id="svg">
<text style="min-height: 43px; margin: 20px; font-size: 200%; font-family: Creepster; font-weight: 400; font-style: normal" x="50%" y="35" text-anchor="middle">FONT</text>
</svg>
<button id="button">render canvas</button>
<img id="img">
<canvas id="canvas"></canvas>
Javascript:
document.getElementById('button').onclick = function() {
var str = new XMLSerializer().serializeToString(document.getElementById('svg'))
var svg = new Blob([str], {type: "image/svg+xml;charset=utf-8"});
var url = self.URL.createObjectURL(svg);
var img = document.getElementById('img');
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
img.onload = function() {
ctx.drawImage(img, 0, 0);
self.URL.revokeObjectURL(url);
};
img.src = url;
}
Notice how the svg renders fine, but when creating the img using the svg's url it fails to render the font correctly, and reverts to Times new Roman.
Any advice? Thanks!
I am trying to add images on button click on canvas. . By default there is 1 image on canvas. Images are getting added on button click, But all images are erased when i click on canvas. Only the background image remains constant.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://code.jquery.com/jquery-1.10.1.js"></script>
<script src="fabric.js"></script>
</script>
<script>
function fun(){
var canvas = window.canvas = new fabric.Canvas('c');
fabric.Image.fromURL('compress/a.jpg', function(img){
canvas.add(img.scale(0.1).set({ left: 150, top: 200, angle: 20 }));
});
$(canvas.wrapperEl).on('mousewheel', function(e) {
var target = canvas.findTarget(e);
var delta = e.originalEvent.wheelDelta / 120;
if (target) {
target.scaleX += delta;
target.scaleY += delta;
// constrain
if (target.scaleX < 0.1) {
target.scaleX = 0.1;
target.scaleY = 0.1;
}
// constrain
if (target.scaleX > 10) {
target.scaleX = 10;
target.scaleY = 10;
}
target.setCoords();
canvas.renderAll();
return false;
}
});
}
function add()
{
window.canvas = new fabric.Canvas('c');
window.canvas.getObjects();
fabric.Image.fromURL('compress/b.jpg', function(img){
window.canvas.add(img.scale(0.1).set({ left: 150, top: 200, angle: 20 }));
window.canvas.selection = true;
window.canvas.renderAll();
window.canvas.calcOffset();
});
}
</script>
<style>
canvas {
border: 1px solid #999;
}
</style>
</head>
<body onload=fun()>
<div id="test" align="center" style="display: block">
<canvas id="c" width="600" height="600"></canvas>
</div>
<button id="but" onclick="add()">add images</button>
</body>
</html>
Please help me with this code
try using canvas.clear() before adding
I'm trying to put the image file "sticky.png" into a canvas box, but all I'm getting is a blank canvas. Can anyone point out what I'm doing wrong and/or give me code that works?
<canvas id="myCanvas" width="200" height="100"
style="border:1px solid #000000;">
</canvas>
<body>
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var sticky = new Image();
sticky.onload = function() {
context.drawImage(sticky, 0, 0);
sticky.src = "sticky.png";
};
</script>
</body>
You need to include the sticky.src before sticky.onload.
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var sticky = new Image();
sticky.src = "sticky.png";
sticky.onload = function() {
context.drawImage(sticky, 0, 0);
};
</script>
</body>
Fiddle
sometimes as a workAround we have to load the image before the canvas. It's very unusual, but it WORKS. And then you just hide the image. Don't forget to use setTimeOut to wait till image is loaded!
setTimeout("paintStar()", 2000);
function paintStar() {
var canva3 = document.getElementById('canvas3');
canva3.width = 640;
canva3.height = 480;
var ct3 = canva3.getContext('2d');
var img = new Image();
img.src = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ3DlDGTyfaFMtUf9GYykLglqfS8GzHbeKRV5vDfHraV1ihNIYo';
ct3.drawImage(img, 0, 0);
ct3.drawImage(img, 0, 0, 20, 20, 10, 200, 20, 20);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CANVAS</title>
<style>
.canvas-1 {
width: 640px;
height: 480px;
border: 1px solid #777;
}
.img-1 {
display: none;
}
</style>
<script src="canva3.js" defer></script>
</head>
<body>
<div class="img-1"><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ3DlDGTyfaFMtUf9GYykLglqfS8GzHbeKRV5vDfHraV1ihNIYo" alt=""></div>
<canvas id="canvas3" style="border: 2px solid #444;">Doesn't work!</canvas>
</body>
</html>
I am generating SVG object using jQuery SVG plug-in. The problem is how can I convert it into image in my script.
My script is following:
<html>
<head>
<script type="text/javascript" src="jquery-latest.min.js"></script>
<script type="text/javascript" src="jquery.svg.js"></script>
<script type="text/javascript">
$(function(){
$("#draw").click(function(){
$('#svg_container').svg();
svg = $('#svg_container').svg('get');
svg.clear(true);
svg.circle(200, 220, 150, {fill: "red", stroke: "blue", strokeWidth: 5});
alert(svg.toSVG()); //this prints svg source of the generated image, i.e. circle
});
});
</script>
</head>
<body>
<div id="svg_container" style="position: absolute; left: 100px; top: 100px; width: 400px; height: 400px; border: thin solid #4297D7;"></div>
<button id="draw">Draw</button>
</body>
</html>
I have tried out this and this but without success.
Could you please show me how to convert this svg into any type of image?
Thanks in advance.
UPDATE
The problem is solved and I have posted the solution as an answer, check it here.
This seams to be very hard to do.
I found this project that attempts to do this:
http://www.svgopen.org/2010/papers/62-From_SVG_to_Canvas_and_Back/index.html
I also found one project that tried to build a SVG renderer for Canvas but it was far from complete.
They did use a solution to go by the server and have the SVG rendered to PNG there, that might be the only really working solution right now.
I have finally solved the problem of converting SVG to image file. Here is the solution, if anybody is interested in:
<html>
<head>
<script type="text/javascript" src="jquery-latest.min.js"></script>
<script type="text/javascript" src="jquery.svg.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/rgbcolor.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/canvg.js"></script>
<script type="text/javascript">
$(function(){
function q(k){
var qs = window.location.search.substring(1);
var t = qs.split("&");
for (i=0;i<t.length;i++) {
kv = t[i].split("=");
if (kv[0] == k) return unescape(kv[1]).replace('+',' ');
}
return null;
}
var context;
function bodyonload() {
if (typeof(FlashCanvas) != 'undefined') context = document.getElementById('canvas').getContext;
var qUrl = q('url'); if (qUrl != null && qUrl != '') { r(); canvg('canvas', qUrl); }
var qSvg = q('svg'); if (qSvg != null && qSvg != '') { r(); canvg('canvas', qSvg); }
}
function render() {
var c = document.getElementById('canvas');
c.width = 400;
c.height = 500;
if (context) c.getContext = context;
canvg(c, document.getElementById('svg').value);
var svg_content = c.toDataURL();
$.ajax({
type:"POST",
url:"svg.php",
data: ({
svg_content: svg_content
}),
timeout: 30000, //30 sec.
});
}
function r() {
var c = document.getElementById('canvas');
c.width = '1000'; //change it to the width of your image
c.height = '600'; //change it to the height of your image
if (context) c.getContext = context;
}
$("#save").click(function(){
render();
});
$("#draw").click(function(){
$('#svg_container').svg();
svg = $('#svg_container').svg('get');
svg.clear(true);
svg.circle(200, 220, 150, {fill: "red", stroke: "blue", strokeWidth: 5});
$("#svg").val(svg.toSVG());
});
});
</script>
</head>
<body>
<textarea id="svg" rows="5" cols="50" style="visibility: hidden;"></textarea><br />
<canvas id="canvas" width="1000px" height="600px"></canvas>
<div id="svg_container" style="position: absolute; left: 100px; top: 100px; width: 400px; height: 400px; border: thin solid #4297D7;"></div>
<button id="draw" style="position: absolute; top:400px; left: 500px;">Draw</button>
<button id="save" style="position: absolute; top:400px; left: 550px;">Save</button>
</body>
</html>
The content of svg.php is following:
<?php
if (isset($_POST['svg_content'])){
$imageData=$_POST['svg_content'];
$filteredData=substr($imageData, strpos($imageData, ",")+1);
$unencodedData=base64_decode($filteredData);
$fp = fopen('test.png', 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
}
?>
You can download jQuery library (jquery-latest.min.js) from jQuery official web site and jQuery SVG library from here .
Hope this will help to many of you who are looking toward converting SVG to image right from your program.
Best,
Bakhtiyor