Using canvas to take a picture of an image element - javascript

I wanted to take a picture of a photo I have on my webpage using a canvas to get a local url for it. Obviously, this is redundant because I already have the url for the photo, but it would be useful in other contexts (like videos). When I execute this code, a white box appears that is not the image I use for testing purpose. Where am I going wrong here?
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="main.js" defer></script>
</head>
<style>
img{
height: 500px;
width: 500px;
}
</style>
<body>
<img id="test" src="img_url">
<button onclick="takePhoto()">Click Me</button>
</body>
</html>
JS:
var width=200
var height=300
function takePhoto(){
var test = document.getElementById("test")
var canvas = document.createElement("canvas")
document.body.appendChild(canvas)
var cxt = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
cxt.drawImage(test, width, height);
var data = canvas.toDataURL('image/png');
console.log(data)
}

The 3 params version of drawImage() is
drawImage(source, x, y);
You did set the x and y params to the width and height of the canvas, which means the browser will draw the image from the bottom right corner of the canvas, which obviously doesn't do much.
You probably wanted the 5 params version
drawImage(source, x, y, resizeWidth, resizeHeight);
Where you'd set x and y to 0.

Related

How to turn an html canvas into an image and then draw that canvas onto the canvas

I'm currently working on an html canvas javascript game, and it's just about finished, but I want to scale up the canvas so the whole game is bigger. I tried using something like
var imgData = ctx.getImageData(0, 0, 300, 500);
ctx.putImageData(imgData,0,0,0,0,360,600)
but using this method I couldn't increase the size of the image. What is the best method for this?
There are multiple ways you can achieve this, the two that i've experimented with would use 2 seperate canvases, putImageData is a little weird, and does not work well for scaling up, what i would recommend, is have a separate canvas, the size of the scaled up version, and then use ctx.drawImage to draw the first canvas on the scaled up version:
var c = document.getElementById('c');
var ctx = c.getContext('2d');
var c2 = document.getElementById('c2');
var ctx2 = c2.getContext('2d')
ctx.fillStyle = "red";
ctx.fillRect(10,10,100,100)
var scaleX = c2.width / c.width;
var scaleY = c2.height / c.height;
ctx2.drawImage(c,0,0,c2.width,c2.height)
canvas{
border: 2px solid black
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<canvas id="c" width="200" height="200"></canvas>
<canvas id="c2" width="400" height="400" ></canvas>
<script src="script.js"></script>
</body>
</html>
The other way is to just scale up the context, then draw the image at 0,0, with no width or height specified:
var c = document.getElementById('c');
var ctx = c.getContext('2d');
var c2 = document.getElementById('c2');
var ctx2 = c2.getContext('2d')
ctx.fillStyle = "red";
ctx.fillRect(10,10,100,100)
var scaleX = c2.width / c.width;
var scaleY = c2.height / c.height;
ctx2.scale(scaleX,scaleY)
ctx2.drawImage(c,0,0)
ctx2.scale(1/scaleX,1/scaleY)
canvas{
border: 2px solid black
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<canvas id="c" width="200" height="200"></canvas>
<canvas id="c2" width="400" height="400" ></canvas>
<script src="script.js"></script>
</body>
</html>
One more option is to use the css scale() tag, but that messes with mouse clicks, and is really annoying so i wouldn't do that. Keep in mind, all methods that scale up the canvas (unless your scaling up coordinates and redrawing), will result in blur.
Hope this helps :D

javascript teechart curved line issue

I want to draw smoothed lines for chart.
I have already made a chart using teechart.js, but it is not good working.
I've attached an image. Left image is mine.
I'd like to make line such as right
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<title>Chart</title>
<script src="./js/three.min.js" type="text/javascript"></script>
<script src="./js/Detector.js" type="text/javascript"></script>
<script src="./js/TrackballControls.js" type="text/javascript"></script>
<script src="./js/helvetiker_regular.typeface.js"></script>
<script src="./js/teechart.js" type="text/javascript"></script>
<script src="./js/teechart-3d.js" type="text/javascript"></script>
<script type="text/javascript">
"use strict";
var three1, Chart1;
function draw() {
three1 = new Tee.Three("canvas1");
three1.setShowShadows(true);
Chart1 = new Tee.Chart(three1);
Chart1.addSeries(new Tee.Line([60,70,70,60,50,40,30,40,50,60,50,40] , 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(',')));
Chart1.addSeries(new Tee.Line([20,30,40,50,60,50,40,50,60,70,70,60]));
Chart1.title.text="";
Chart1.footer.text="";
Chart1.legend.visible = false;
Chart1.walls.back.size=0.2;
Chart1.walls.left.size=10;
Chart1.walls.bottom.size=10;
Chart1.walls.back.format.transparency=0.2;
Chart1.bounds.x = -100;
Chart1.bounds.y = 50;
Chart1.bounds.width = 900;
Chart1.bounds.height = 400;
Chart1.axes.left.setMinMax(0, 120);
if (three1.isEnabled()) {
Chart1.draw();
animate1();
} else {
// Show message (WebGL not available) :
Detector.addGetWebGLMessage();
// Disable WebGL and use HTML5 2D Canvas:
three1.setEnabled(false, Chart1);
}
// Loop
function animate1() {
three1.update();
requestAnimationFrame(animate1);
}
}
</script>
</head>
<body onload="draw()">
<canvas id="canvas1" style="width: 700px; height: 500px; display: inline; background: white;" width="800" height="500"></canvas>
</body>
</html>
Hope good answers.
Checking your code I see it misses a couple of details, but correcting them it works without problems:
Set smoothed lines. In your example it would be:
Chart1.series.items[0].smooth = 0.5;
Chart1.series.items[1].smooth = 0.5;
Include teechart-extras.js to define Tee.drawSpline. It would be something like this:
<script src="./js/teechart-extras.js" type="text/javascript"></script>
I think you should take a look at THREE.TubeGeometry where you can pass a spline/curve as a path for the tube:
extrudePath = // define some spline or curve;
segments = 64;
radius = 5;
radiusSegments = 8;
closed = false;
tube = new THREE.TubeGeometry( extrudePath, segments, radius, radiusSegments, closed );
mesh = new THREE.Mesh( tube, material );
scene.add( mesh );
Check also the examples here

Automatically resize Html5 canvas with respect to the screen resolution

I have created an HTML5 canvas game which involves dragging and selecting objects(words) from two canvases. The screen also has two buttons. But unfortunately my program is hard coded in terms of selecting words as I have entered the co-ordinates where the words are drawn on canvas. My screen resolution is 1366 x768. Now whenever the resolution is changed, the buttons move somewhere else and the mouse never selects the dragged words rather some words else above it. I am in a big trouble now, please help !!
<html>
<head>
<title>Word Search</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type = text/css href="style.css">
<script type="text/javascript" src="keywords.js"></script>
<script type="text/javascript" src="game.js"></script>
<script type="text/javascript" src="highlight.js"></script>
<script type="text/javascript" src="grid.js"></script>
<script src="http://code.createjs.com/easeljs-0.7.0.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<h1 id="heading">Find Keywords</h1>
<h3 id="results">Drag through the lettered Squares..!</h3>
<canvas id ='canvas1' height = 450 width="450" style= "border :1px solid black"> </canvas>
<canvas id ='canvas2' height = 450 width="250" style= "border :1px solid black"></canvas>
<input type='button' value="HIGHLIGHT ALL" id="button1" onclick="highlight();" />
<input type='button' value="NEXT" id="button2" onclick="next();"/>
<script>
var words =[];
window.onload = function(){
begin();
};
function begin()
{
wordSearchPuzzle();
}
function wordSearchPuzzle()
{
words.length=0;
words = getwords(8);
var puz =wordfind(words);
game(words,puz);
}
function next()
{
var canvas = document.getElementById("canvas1");
var ctx1 = canvas.getContext("2d");
var canvas2 = document.getElementById("canvas2");
var ctx2 = canvas2.getContext("2d");
ctx1.clearRect(0, 0, canvas.width, canvas.height);
ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
wordSearchPuzzle();
}
</script>
</body>
</html>
This is possible, I have done it int he past with a canvas that would be dynamically sized based on the screen size.
If I remember correctly i did something like this.
I placed the canvas in a div, and gave the div a dynamic width, something like style="width: 30%"
I placed the canvas inside this div and tied css to give the canvas a style="width: 100%"
<div style="width:30%">
<canvas id="can" style="width:100%"></canvas>
</div>
I tied into the window resized event and read the client size to determine the element width and height to change the canvas
window.resize = function(){
var canvas = document.getElementById("can");
canvas.width = canvas.clientWidth;
canvas.height = //some value based on width
}
You then need to redraw your canvas as resizing will clear the canvas of all content

screen resolution geeksphone peak

in specification of FFOS GP PEAK is written, that it's got qHD display (it is 960*540), but when I run JavaScript code:
console.log(screen.width)
console.log(screen.height)
I get 640*360. Is it JavaScript bug? Or anything else?
Thank you.
I believe the Peak has a device pixel ratio of 1.5, which would be 640x360 logical pixels.
You may want to have a look at css - what exactly is device pixel ratio
and Bug 838505
If I use the following HTML and JS this draws a square around the entire screen.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<!--<meta name = "viewport" content="user-scalable = no"> -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" type="text/css" href="css/background.css">
<title>Test</title>
<script type="text/javascript" src="js/loop.js"></script>
<style type="text/css">
*
{
border: 0px;
margin: 0px;
padding: 0px;
}
</style>
</head>
<body><canvas id="myCanvas"></canvas></body>
</html>
loop.js
//Main file for game logic
window.onload = init;
//Setup function to reset start location
function setup() {
canvas = document.getElementById('myCanvas');
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
context = canvas.getContext('2d');
context.beginPath();
context.lineWidth="6";
context.strokeStyle="red";
context.rect(0,0,canvas.width,canvas.height);
context.stroke();
}
//Initialize game and event handlers
function init() {
setup();
}

Why can't I draw a rectangle in my HTML5 canvas?

I am trying to draw a red rectangle on my HTML5 canvas. Here is my HTML.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<title>My Canvas Experiment</title>
<link rel="stylesheet" type="text/css" href="main.css" />
<script src="plotting.js"></script>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js">
</script>
<![endif]-->
</head>
<body>
<canvas id="plot"></canvas>
</body>
</html>
Here is plotting.js:
document.onload = function() {
var c = document.getElementById("plot");
var ctx = c.getContext("2d");
ctx.fillStyle("#f00");
ctx.fillRect(0, 0, 175, 40);
}
Here is main.css:
body { margin:100px; }
article, aside, figure, footer, header, hgroup, menu, nav, section {
display:block;
}
#plot {
width: 500px;
height: 400px;
}
Why is the page blank? Chrome Web Developer Console issues no errors.
Replace:
ctx.fillStyle("#f00");
with:
ctx.fillStyle="#f00";
Use window.onload instead of document.onload, (keeping #stewe's suggestion).
DEMO
Replacectx.fillStyle('#f00'); to ctx.fillStyle = 'red'; because fillStyle is a variable and NOT the function.
I've been having issues all morning with javascript not drawing my shapes. Turns out you HAVE to set the width and height on the canvas tag in HTML, and not through the CSS, or the shapes will not draw.
example:
<canvas id="map" width="500" height="500"></canvas>

Categories