I'm new to javascript and web development in general, and I'm trying to write a renderer that can draw each slice in a CT scan as a 2D image.
I have a long thin (512x49664) image made from 512x97 slices, each of which is just a 512x512 image. I've already ascertained that this will upset webgl, so I was planning to grab individual slices from the image by drawing it on a canvas and copying the image data into a texture.
My question is: if I have a function in which I do something like:
// Create a small canvas to contain a single slice.
function getSlice(sliceNumber){
var sliceCanvas = document.createElement("canvas");
sliceCanvas.width = 512;
sliceCanvas.height = 512;
var sliceContext = sliceCanvas.getContext('2d');
sliceContext.drawImage(image, 0, 512*sliceNumber, 512, 512, 0, 0, 512, 512);
}
What happens to the canvas I created when the function exits?
It hasn't been:
Added to the DOM
Stored in a variable or property that is still in scope
Returned anywhere
… there are no references remaining to it, so it will be marked for garbage collection.
When you create a DOM element via javascript DOM API, you should attach this element to the page document.
Otherwise this element will never shown in your page.
So you have to add a line like this in your code:
document.body.appendChild(sliceCanvas);
If you call your function multiple times, you should check the canvas creation:
var sliceCanvas = document.getElementsByTagName('canvas')[0];
or
var sliceCanvas = document.getElementById('myCanvasId');
Then check:
if (!sliceCanvas) {
sliceCanvas = document.createElement('canvas');
sliceCanvas.id = 'myCanvasId'; // optional
document.body.appendChild(sliceCanvas);
}
// here your code...
UPDATE:
Consider to change the document.body with the proper DOM element where you want to place your canvas.
Related
I'm new to PixiJS and I'm trying something simple like a painting application.
I'm having difficulty trying to capture a collection of shapes as a single grouping. I'm not interested in working code for this as I'd like to figure that out on my own; I'm simply interested in knowing whether I'm on the right track or if I need to explore some other PixiJS concepts to get what I need.
I have one canvas in which I can drag shapes such as rectangles, ellipse, and lines. These "strokes" are being stored as individual Graphics objects, for instance:
var shape = new PIXI.Graphics();
shape.position.set(...);
...
shape.lineStyle(...)
.beginFill(...)
.drawRect(...)
.endFill();
...
stage.addChild(shape);
...
renderer.render(stage);
I'm also holding onto these shapes in an array:
shapes.push(shape);
Now that I have these displayed as well as have the order of the strokes available, I'd like to be able to capture them somehow. Imagine maybe taking the drawing and saving it, or perhaps using it as a thumbnail in a gallery, or simply just storing it on the back-end in a database, preferably keeping all the raw strokes so that they can be scaled up or down as desired.
For now, I'm simply trying to take this collection of strokes and display them again by holding them, clearing the graphics from my canvas, and then plopping down what I have held.
Looking at this example, I've been able to get a texture that I can reliably reproduce wherever I click with the mouse:
http://jsfiddle.net/gzh14bcn/
This means I've been able to take the first part that creates the texture object, and I tweaked the second part to create and display the sprites when I click the mouse.
When I try to replace this example code with my own code to create the texture itself, I can't get that part to work.
So this example snippet works fine when I try to create a sprite from it:
var texture = new PIXI.RenderTexture(renderer, 16, 16);
var graphics = new PIXI.Graphics();
graphics.beginFill(0x44FFFF);
graphics.drawCircle(8, 8, 8);
graphics.endFill();
texture.render(graphics);
FYI to create sprites:
var sprite = new PIXI.Sprite(texture);
sprite.position.set(xPos, yPos);
stage.addChild(sprite);
Since I have my shapes in the shapes array or on the stage, what is the preferred way I proceed to capture this as a single grouping from which I can create one or more sprites?
So basicaly you've got how to make some PIXI.Graphics shape
var pixiRect = new PIXI.Graphics();
pixiRect.lineStyle(..);
pixiRect.beginFill(..);
pixiRect.drawRect(..);
pixiRect.endFill(..);
(You can draw as many rects/circles/shapes as you want into one PIXI.Graphics)
But to convert it to texture you must tell renderer to create it
var texture = renderer.generateTexture(pixiRect);
Then you can easily create PIXI.Sprite from this texture
var spr = new PIXI.Sprite(texture);
And the last thing is to add it to your stage or array, but you can also make some empty PIXI.Container and then addChild to that and you've got your array
option - add sprite (created from graphics) to stage
stage.addChild(spr);
option - push it to your array
shapes.push(spr);
option - if you have var shapes = new PIXI.Container(); you can make a container for your sprites
shapes.addChild(spr);
Working example : https://jsfiddle.net/co7Lrbq1/3/
EDIT:
to position your canvas above you have to addChild it later, it means first addChild has zIndex = 0 and every addChild adds a layer on top of last
I figured it out. My stage is a container:
var stage = new PIXI.Container();
var canvas = new PIXI.Graphics();
canvas.lineStyle(4, 0xffffff, 1);
canvas.beginFill(0xffffff);
canvas.drawRect(canvasStartX, canvasStartY, 500, 600);
canvas.endFill();
stage.addChild(canvas);
I changed this to the following:
var canvas = new PIXI.Container();
var canvasRect = new PIXI.Graphics();
canvasRect.lineStyle(4, 0xffffff, 1);
canvasRect.beginFill(0xffffff);
canvasRect.drawRect(canvasStartX, canvasStartY, 500, 600);
canvasRect.endFill();
canvas.addChild(canvasRect);
stage.addChild(canvas);
Then, I replaced stage with canvas where appropriate and canvas with canvasRect where appropriate.
Finally, I got my texture with:
var texture = canvas.generateTexture(renderer);
At the moment, this grabbed the entire width/height of the stage, but I think I just need to tweak a bit on how I create my canvas above and I should be fine.
I'd like to dynamically downsize some images on my canvas using createjs, and then store the smaller images to be displayed when zooming out of the canvas for performance reasons. Right now, I'm using the following code:
var bitmap = createjs.Bitmap('somefile.png');
// wait for bitmap to load (using preload.js etc.)
var oc = document.createElement('canvas');
var octx = oc.getContext('2d');
oc.width = bitmap.image.width*0.5;
oc.height = bitmap.image.height*0.5;
octx.drawImage(bitmap.image, 0, 0, oc.width, oc.height);
var dataUrl = oc.toDataURL('image/png'); // very expensive
var smallBitmap = new createjs.Bitmap(dataUrl);
This works, but:
The toDataURL operation is very expensive when converting to image/png and too slow to use in practice (and I can't convert to the faster image/jpeg due to the insufficient quality of the output for all settings I tried)
Surely there must be a way to downsize the image without having to resort to separate canvas code, and then do a conversion manually to draw onto the createjs Bitmap object??
I've also tried:
octx.drawImage(bitmap.image, 0, 0, oc.width, oc.height);
var smallBitmap = new createjs.Bitmap(oc);
But although very fast, this doesn't seem to actually work (and in any case I'm having to create a separate canvas element every time to facilitate this.)
I'm wondering if there is a way that I can use drawImage to draw a downsampled version of the bitmap into a createjs Bitmap instance directly without having to go via a separate canvas object or do a conversion to string?
If I understand correctly, internally this is how the createjs cache property works (i.e. uses drawImage internally to write into the DisplayObject) but I'm unable to figure out how use it myself.
You have tagged this post with createjs and easeljs, but your examples show plain Canvas context usage for scaling.
You can use the scale parameter on Bitmap.cache() to get the result you want, then reuse the cacheCanvas as necessary.
// This will create a half-size cache (50%)
// But scale it back up for you when it displays on the stage
var bmp = new createjs.Bitmap(img);
bmp.cache(0, 0, img.width, img.height, 0.5);
// Pull out the generated cache and use it in a new Bitmap
// This will display at the new scaled size.
var bmp2 = new createjs.Bitmap(bmp.cacheCanvas);
// Un-cache the first one to reset it if you want
bmp.uncache();
Here is a fiddle to see it in action: http://jsfiddle.net/lannymcnie/ofdsyn7g/
Note that caching just uses another canvas with a drawImage to scale it down. I definitely would stay away from toDataURL, as it not performant at all.
I am beginning to explore the HTML5 canvas, and I apologize in advance for the naivety of my question. Using Flash CC, I have generated a canvas with a rectangle on it:
(function (lib, img, cjs, ss) {
var p; // shortcut to reference prototypes
// library properties:
lib.properties = {
width: 550,
height: 400,
fps: 24,
color: "#FFFFFF",
manifest: []
};
// symbols:
// stage content:
(lib.canvas_test = function() {
this.initialize();
// Layer 1
this.shape = new cjs.Shape();
this.shape.graphics.beginFill().beginStroke("#669966")
.setStrokeStyle(1,1,1).moveTo(-94,-62).lineTo(94,-62).lineTo(94,62).lineTo(-94,62).closePath();
this.shape.setTransform(198,136);
this.shape_1 = new cjs.Shape();
this.shape_1.graphics.beginFill("#FF933C")
.beginStroke().moveTo(-94,62).lineTo(-94,-62).lineTo(94,-62).lineTo(94,62).closePath();
this.shape_1.setTransform(198,136);
this.addChild(this.shape_1,this.shape);
}).prototype = p = new cjs.Container();
p.nominalBounds = new cjs.Rectangle(378,273,190,126);
})(lib = lib||{}, images = images||{}, createjs = createjs||{}, ss = ss||{});
var lib, images, createjs, ss;
Now I am stuck. How can I retrieve (and change) the color of the rectangle using a Javascript function? I had hoped that the shapes would simply be children of the canvas, but this does not seem to be the case.
The earlier answers are correct about Canvas being basically a bitmap, but EaselJS gives you a retained graphics mode, so you can change properties and update the stage/canvas to reflect them.
You are using Flash export to generate your content, so you should be able to access your elements via the exportRoot, which is created in the HTML. This is essentially the Flash "stage", represented by an EaselJS container that is defined by canvas_test in your exported library.
exportRoot = new lib.canvas_test();
You can see in the canvas_test code, each "child" is defined. Any graphics are wrapped in EaselJS Shape instances. There are also classes for handling groups (Containers), Bitmaps, Text, and animations (MovieClips).
Here is your exported code above put added to the stage:
http://jsfiddle.net/lannymcnie/b5me4xa2/
It is easy to modify shapes once they are created, but you have to define them with that in mind. The Flash export doesn't really provide you this capability, since it just exports everything as a single, chained graphics instructions list. You can however introspect it fairly easily to find the commands you want to modify. Warning: This requires EaselJS 0.7.0+ in order to work. Earlier versions will not work with this approach
The demo you provided has a single Rectangle. Unfortunately there is a bug in the current version of Flash that exports it as 2 shapes, one for the stroke, and another for the fill. This example will modify the stroke.
var shape = exportRoot.shape; // Access the shape instance that has the stroke
var stroke = shape.graphics._stroke;
stroke.style = "#ff0000"; // Set to red.
To do the fill, you can do the same thing on shape_1, but affect the _fill instead. Here is an updated sample
You can also access any of the instructions, and affect their properties. You can see a full command list in the Graphics docs (see the sidebar for the full list). Here is a quick sample modifying the first moveTo command on the stroke:
var shape = exportRoot.shape;
shape.graphics._activeInstructions[0].x = -110;
You can see a sample of that code here: http://jsfiddle.net/lannymcnie/b5me4xa2/2/ -- You will have to modify both fill and stroke to move them both :)
Canvas is basically a bitmap, it has no children. An SVG works more like you're imagining but a canvas just has pixels. If you want to change a canvas you're either going to have to go through it and find the pixels, or create a javascript object representing your drawing object (the rectangle), keep it separate from your canvas background, and redraw the the background and object when there are any changes.
[Added]
I'm not familiar with Flash CC, but as pointed out in the comment, perhaps there is some capability there already to do what the commenter and myself are describing - I'm afraid I don't know.
I want to load an image, copy it e.g. 2 times, and manipulate the other 2 images. Somehow I want to do some "post-processing" stuff with the two clones. I DON'T want to get canvas parts and manipulate them. I am programming a realtime 2D game and it would be madness to manipulate every image within every frame.
Many of the solutions I found were just "cutting" parts from the canvas, dealing with them and writing them back onto the canvas. But I want to have the manipulated images stored in imageObjects to be able to directly draw them as if they were the "real" image.
A canvas is still the best way of manipulating images. Canvas slices that you get via context.getImageData() can be painted back via context.putImageData() (see Pixel manipulation with canvas) so I don't see a real advantage of converting image data into images. However, if you prefer a "real" image object, you can use canvas.toDataURL() and create an image object with this URL. Something along these lines:
// Create temporary canvas
var canvas = document.createElement("canvas");
canvas.setAttribute("width", imageData.width);
canvas.setAttribute("height", imageData.height);
// Put image data into canvas
var context = canvas.getContext("2d");
context.putImageData(imageData, 0, 0);
// Extract canvas data into an image object
var image = new Image();
image.src = canvas.toDataURL("image/png");
image.onload = function() {alert("Image object can be used")};
I am currently looking for a way to create a canvas 2d rendering context without actually having a canvas element on the page. I could dynamically create a canvas element and hide it, but then again I don't want to show the image directly to the user anytime, so there's no point of actually having a canvas element in the page. So I'm basicly looking for something that is similar to
var image = new Image( );
but only for canvas 2d rendering context (pseudo code)
var context = new 2dContext( );
Is there functionality like this? I wasn't able to find anything like it. Calling
var context = new CanvasRenderingContext2D( );
which is the name of the rendering context interface by HTML5 spec just gives me awkward errors in Firefox:
uncaught exception: [Exception... "Cannot convert WrappedNative to function" nsresult: "0x8057000d (NS_ERROR_XPC_CANT_CONVERT_WN_TO_FUN)" location: "JS frame :: http://localhost/ :: <TOP_LEVEL> :: line 25" data: no]
It is possible to use a canvas without displaying it on the page. You could do the following:
// Create a canvas element
var canvas = document.createElement('canvas');
canvas.width = 500;
canvas.height = 400;
// Get the drawing context
var ctx = canvas.getContext('2d');
// Then you can do stuff, e.g.:
ctx.fillStyle = '#f00';
ctx.fillRect(20,10,80,50);
Once you've used the canvas, you can of course add it to the document
var element = document.getElementById('canvas_container');
element.appendChild(canvas);
Or you could make an image from it:
var new_image_url = canvas.toDataURL();
var img = document.createElement('img');
img.src = new_image_url;
Or you could access the canvas data as values with:
var image_data = ctx.getImageData(0, 0, canvas.width, canvas.height);
var rgba_byte_array = image_data.data;
rgba_byte_array[0]; // red value for first pixel (top left) in the canvas
Interestingly enough, if you create a canvas object and store its context in a variable, that variable has its own pointer to the canvas object. Since you can't use getContext("2d") without a canvas, you might as well only have one canvas pointer. If you're like me and hate having a two references to the same object, you could do this:
Original:
var canvas=document.createElement("canvas");
var context=canvas.getContext("2d");
alert(Boolean(context.canvas==canvas));// true.
What I'm talking about:
var context=document.createElement("canvas").getContext("2d");
alert(context.canvas);// The canvas object.
Now you can do all of your important canvas stuff through the context variable. After all, context is accessed more often than the canvas variable. When you do need it just reference it through the context:
context.canvas.width=320;
context.canvas.height=320;
document.body.appendChild(context.canvas);
And if you don't want to bother with the canvas just leave the variable alone, it's not like you wanted to use it anyway.
How about: OffscreenCanvas()?
And the answer is probably no, since this is only supported in Firefox 44.0+ currently.
var offscreen = new OffscreenCanvas(256, 256);
https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas
https://html.spec.whatwg.org/multipage/scripting.html#the-offscreencanvas-interface
(Added for reference here, as this may well be new to the spec since this question was asked more than 6 years ago! And hopefully will be more widely adopted)